From 77f5ad9569a2e391a9d3f0e7282b4720e4744b2d Mon Sep 17 00:00:00 2001
From: diegolmello <diegolmello@gmail.com>
Date: Thu, 21 Feb 2019 13:56:31 -0300
Subject: [PATCH] Testing

---
 app/lib/database/helpers/messages.js      |  1 -
 app/lib/database/helpers/subscriptions.js | 20 +++----
 app/lib/database/index.js                 |  4 +-
 app/lib/methods/loadMessagesForRoom.js    |  9 +--
 app/lib/realm.js                          |  6 +-
 app/views/RoomView/ListView.js            | 71 +++++++++++++++--------
 app/views/RoomView/index.js               | 67 ++++++++++++++++-----
 7 files changed, 121 insertions(+), 57 deletions(-)

diff --git a/app/lib/database/helpers/messages.js b/app/lib/database/helpers/messages.js
index b8e4d8288..09fafeb60 100644
--- a/app/lib/database/helpers/messages.js
+++ b/app/lib/database/helpers/messages.js
@@ -5,7 +5,6 @@ export const createMessage = (db, message) => {
 	db.action(async(action) => {
 		const messagesCollection = db.collections.get('messages');
 		message = buildMessage(message);
-		console.log('TCL: createMessage -> message', message);
 		let messageRecord;
 		try {
 			messageRecord = await messagesCollection.find(message.id);
diff --git a/app/lib/database/helpers/subscriptions.js b/app/lib/database/helpers/subscriptions.js
index 6923507c6..e50f94258 100644
--- a/app/lib/database/helpers/subscriptions.js
+++ b/app/lib/database/helpers/subscriptions.js
@@ -17,7 +17,7 @@ export const createSubscription = (db, subscription) => {
 					s.roomUpdatedAt = subscription.room_updated_at;
 				}
 			});
-			await action.subAction(() => subscriptionRecord.deleteRoles());
+			// await action.subAction(() => subscriptionRecord.deleteRoles());
 		} catch (error) {
 			subscriptionRecord = await subscriptionsCollection.create((s) => {
 				s._raw = sanitizedRaw({
@@ -29,15 +29,15 @@ export const createSubscription = (db, subscription) => {
 			});
 		}
 
-		if (subscription.roles) {
-			subscription.roles.forEach(async(role) => {
-				try {
-					await action.subAction(() => subscriptionRecord.addRole(role));
-				} catch (error) {
-					console.log('Error creating subscriptionRole -> error', error);
-				}
-			});
-		}
+		// if (subscription.roles) {
+		// 	subscription.roles.forEach(async(role) => {
+		// 		try {
+		// 			await action.subAction(() => subscriptionRecord.addRole(role));
+		// 		} catch (error) {
+		// 			console.log('Error creating subscriptionRole -> error', error);
+		// 		}
+		// 	});
+		// }
 	});
 };
 
diff --git a/app/lib/database/index.js b/app/lib/database/index.js
index c661cc49b..96c330400 100644
--- a/app/lib/database/index.js
+++ b/app/lib/database/index.js
@@ -46,5 +46,5 @@ export const appDatabase = new Database({
 });
 
 
-// serverDatabase.unsafeResetDatabase();
-// appDatabase.unsafeResetDatabase();
\ No newline at end of file
+serverDatabase.unsafeResetDatabase();
+appDatabase.unsafeResetDatabase();
\ No newline at end of file
diff --git a/app/lib/methods/loadMessagesForRoom.js b/app/lib/methods/loadMessagesForRoom.js
index c9f63528f..aa6633f09 100644
--- a/app/lib/methods/loadMessagesForRoom.js
+++ b/app/lib/methods/loadMessagesForRoom.js
@@ -22,9 +22,9 @@ async function load({ rid: roomId, latest, t }) {
 	}
 
 	let params = { roomId, count: 50 };
-	// if (latest) {
-	// 	params = { ...params, latest: new Date(latest).toISOString() };
-	// }
+	if (latest) {
+		params = { ...params, latest: new Date(latest).toISOString() };
+	}
 	// RC 0.48.0
 	const data = await this.sdk.get(`${ this.roomTypeToApiType(t) }.history`, params);
 	if (!data || data.status === 'error') {
@@ -50,9 +50,10 @@ export default function loadMessagesForRoom(...args) {
 						dbActions.push(createMessage(appDatabase, message));
 					});
 					await Promise.all(dbActions);
+					return resolve(data);
 				});
 			} else {
-				return resolve();
+				return resolve([]);
 			}
 		} catch (e) {
 			log('loadMessagesForRoom', e);
diff --git a/app/lib/realm.js b/app/lib/realm.js
index 3365acce8..651abdffd 100644
--- a/app/lib/realm.js
+++ b/app/lib/realm.js
@@ -1,8 +1,8 @@
 import Realm from 'realm';
 
-// import { AsyncStorage } from 'react-native';
-// Realm.clearTestState();
-// AsyncStorage.clear();
+import { AsyncStorage } from 'react-native';
+Realm.clearTestState();
+AsyncStorage.clear();
 
 const serversSchema = {
 	name: 'servers',
diff --git a/app/views/RoomView/ListView.js b/app/views/RoomView/ListView.js
index 28935f5ab..f1ad55142 100644
--- a/app/views/RoomView/ListView.js
+++ b/app/views/RoomView/ListView.js
@@ -6,6 +6,7 @@ import {
 import moment from 'moment';
 import { connect } from 'react-redux';
 import PropTypes from 'prop-types';
+import withObservables from '@nozbe/with-observables';
 
 import Separator from './Separator';
 import styles from './styles';
@@ -14,6 +15,8 @@ import scrollPersistTaps from '../../utils/scrollPersistTaps';
 import debounce from '../../utils/debounce';
 import RocketChat from '../../lib/rocketchat';
 import log from '../../utils/log';
+import { appDatabase } from '../../lib/database';
+import { Q } from '@nozbe/watermelondb';
 
 const DEFAULT_SCROLL_CALLBACK_THROTTLE = 100;
 
@@ -30,7 +33,7 @@ export class DataSource extends OldList.DataSource {
 
 const ds = new DataSource({ rowHasChanged: (r1, r2) => r1._id !== r2._id });
 
-export class List extends React.Component {
+class List extends React.Component {
 	static propTypes = {
 		onEndReached: PropTypes.func,
 		renderFooter: PropTypes.func,
@@ -40,50 +43,63 @@ export class List extends React.Component {
 
 	constructor(props) {
 		super(props);
-		this.data = database
-			.objects('messages')
-			.filtered('rid = $0', props.room.rid)
-			.sorted('ts', true);
+		// this.data = database
+		// 	.objects('messages')
+		// 	.filtered('rid = $0', props.room.rid)
+		// 	.sorted('ts', true);
 		this.state = {
-			loading: true,
+			loading: false,
 			loadingMore: false,
 			end: false
 		};
-		this.dataSource = ds.cloneWithRows(this.data);
+		this.dataSource = ds.cloneWithRows(this.props.messages);
 	}
 
-	componentDidMount() {
-		this.updateState();
-		this.data.addListener(this.updateState);
-	}
+	// componentDidMount() {
+	// 	this.updateState();
+	// 	this.data.addListener(this.updateState);
+	// }
 
-	shouldComponentUpdate(nextProps, nextState) {
-		const { loadingMore, loading, end } = this.state;
-		return end !== nextState.end || loadingMore !== nextState.loadingMore || loading !== nextState.loading;
-	}
+	// shouldComponentUpdate(nextProps, nextState) {
+	// 	const { loadingMore, loading, end } = this.state;
+	// 	return end !== nextState.end || loadingMore !== nextState.loadingMore || loading !== nextState.loading;
+	// }
+
+	// componentWillUnmount() {
+	// 	this.data.removeAllListeners();
+	// 	this.updateState.stop();
+	// }
+
+	// componentDidUpdate() {
+	// 	this.updateState();
+	// }
 
-	componentWillUnmount() {
-		this.data.removeAllListeners();
-		this.updateState.stop();
+	componentWillReceiveProps(nextProps) {
+		if (nextProps.messages.length !== this.props.messages.length) {
+			this.updateState();
+		}
 	}
 
 	// eslint-disable-next-line react/sort-comp
 	updateState = debounce(() => {
 		this.setState({ loading: true });
-		this.dataSource = this.dataSource.cloneWithRows(this.data);
+		// this.dataSource = this.dataSource.cloneWithRows(this.data);
+		this.dataSource = this.dataSource.cloneWithRows(this.props.messages);
 		this.setState({ loading: false });
 	}, 300);
 
 	onEndReached = async() => {
 		const { loadingMore, end } = this.state;
-		if (loadingMore || end || this.data.length < 50) {
+		const { messages } = this.props;
+		if (loadingMore || end || messages.length < 50) {
 			return;
 		}
 
 		this.setState({ loadingMore: true });
 		const { room } = this.props;
 		try {
-			const result = await RocketChat.loadMessagesForRoom({ rid: room.rid, t: room.t, latest: this.data[this.data.length - 1].ts });
+			const result = await RocketChat.loadMessagesForRoom({ rid: room.rid, t: room.t, latest: messages[messages.length - 1].ts });
+			console.log('TCL: List -> onEndReached -> result', result);
 			this.setState({ end: result.length < 50, loadingMore: false });
 		} catch (e) {
 			this.setState({ loadingMore: false });
@@ -100,13 +116,13 @@ export class List extends React.Component {
 	}
 
 	render() {
-		const { renderRow } = this.props;
+		const { renderRow, messages } = this.props;
 
 		return (
 			<ListView
 				enableEmptySections
 				style={styles.list}
-				data={this.data}
+				data={messages}
 				keyExtractor={item => item._id}
 				onEndReachedThreshold={100}
 				renderFooter={this.renderFooter}
@@ -122,6 +138,15 @@ export class List extends React.Component {
 	}
 }
 
+const enhance = withObservables(['room'], ({ room }) => ({
+	messages: appDatabase.collections.get('messages').query(
+		Q.where('rid', room.rid)
+	).observe()
+}));
+const EnhancedList = enhance(List);
+
+export default EnhancedList;
+
 @connect(state => ({
 	lastOpen: state.room.lastOpen
 }))
diff --git a/app/views/RoomView/index.js b/app/views/RoomView/index.js
index 45ab88ca8..cf81b1925 100644
--- a/app/views/RoomView/index.js
+++ b/app/views/RoomView/index.js
@@ -7,15 +7,17 @@ import { connect } from 'react-redux';
 import { RectButton } from 'react-native-gesture-handler';
 import SafeAreaView from 'react-native-safe-area-view';
 import equal from 'deep-equal';
+import withObservables from '@nozbe/with-observables';
 
 import Navigation from '../../lib/Navigation';
 import { openRoom as openRoomAction, closeRoom as closeRoomAction, setLastOpen as setLastOpenAction } from '../../actions/room';
 import { toggleReactionPicker as toggleReactionPickerAction, actionsShow as actionsShowAction } from '../../actions/messages';
 import LoggedView from '../View';
-import { List } from './ListView';
+import List from './ListView';
 import database from '../../lib/realm';
 import RocketChat from '../../lib/rocketchat';
 import Message from '../../containers/message';
+import MessageComponent from '../../containers/message/Message';
 import MessageActions from '../../containers/MessageActions';
 import MessageErrorActions from '../../containers/MessageErrorActions';
 import MessageBox from '../../containers/MessageBox';
@@ -27,6 +29,8 @@ import { isIOS } from '../../utils/deviceInfo';
 import I18n from '../../i18n';
 import Icons from '../../lib/Icons';
 import ConnectionBadge from '../../containers/ConnectionBadge';
+import { appDatabase } from '../../lib/database';
+import { Q } from '@nozbe/watermelondb';
 
 @connect(state => ({
 	user: {
@@ -46,7 +50,7 @@ import ConnectionBadge from '../../containers/ConnectionBadge';
 	closeRoom: () => dispatch(closeRoomAction())
 }))
 /** @extends React.Component */
-export default class RoomView extends LoggedView {
+class RoomView extends LoggedView {
 	static options() {
 		return {
 			topBar: {
@@ -102,6 +106,7 @@ export default class RoomView extends LoggedView {
 		};
 		this.onReactionPress = this.onReactionPress.bind(this);
 		Navigation.events().bindComponent(this);
+		console.log(this.props.messages)
 	}
 
 	componentDidMount() {
@@ -311,23 +316,48 @@ export default class RoomView extends LoggedView {
 
 	renderItem = (item, previousItem) => {
 		const { room } = this.state;
-		const { user } = this.props;
+		// const { user } = this.props;
+
+		const user = {
+			id: 'y8bd77ptZswPj3EW8',
+			username: 'diego.mello',
+			token: '79q6lH40W4ZRGLOshDiDiVlQaCc4f_lU9HNdHLAzuHz'
+		};
+		const author = {
+			_id: 'userid',
+			username: 'diego.mello'
+		};
+		const baseUrl = 'https://open.rocket.chat';
+		const customEmojis = { react_rocket: 'png', nyan_rocket: 'png', marioparty: 'gif' };
+		const date = new Date(2017, 10, 10, 10);
 
 		return (
-			<Message
-				key={item._id}
-				item={item}
-				status={item.status}
-				reactions={JSON.parse(JSON.stringify(item.reactions))}
+			<MessageComponent
+				baseUrl={baseUrl}
+				customEmojis={customEmojis}
 				user={user}
-				archived={room.archived}
-				broadcast={room.broadcast}
-				previousItem={previousItem}
-				_updatedAt={item._updatedAt}
-				onReactionPress={this.onReactionPress}
-				onLongPress={this.onMessageLongPress}
+				author={author}
+				ts={date}
+				timeFormat='LT'
+				header
 			/>
 		);
+
+		// return (
+		// 	<Message
+		// 		key={item._id}
+		// 		item={item}
+		// 		status={item.status}
+		// 		// reactions={JSON.parse(JSON.stringify(item.reactions))}
+		// 		user={user}
+		// 		archived={room.archived}
+		// 		broadcast={room.broadcast}
+		// 		// previousItem={previousItem}
+		// 		_updatedAt={item._updatedAt}
+		// 		onReactionPress={this.onReactionPress}
+		// 		onLongPress={this.onMessageLongPress}
+		// 	/>
+		// );
 	}
 
 	renderFooter = () => {
@@ -401,3 +431,12 @@ export default class RoomView extends LoggedView {
 		);
 	}
 }
+
+const enhance = withObservables(['rid'], ({ rid }) => ({
+	messages: appDatabase.collections.get('messages').query(
+		Q.where('rid', rid)
+	).observe()
+}));
+const EnhancedRoomView = enhance(RoomView);
+
+export default EnhancedRoomView;
-- 
GitLab