import { actionPromise } from "./actionsPromise";
import { gql } from "../helpers/gql";
import { actionAddMessages } from "./actionsMessages";


export const actionGetMessageForChat = (_id, fromChatItem) => 
	async (dispatch,getState) => {
		let messLen = fromChatItem ? 0 : Object.values(getState().chats[_id]?.messages || {}).length; 

		let messages = await dispatch(
			actionPromise('messages', gql(`query FindMessChat($chat: String) {
				MessageFind(query: $chat) {
				  _id
				  text
				  createdAt
				  chat{
					  _id
				  }
				  media {
					url
					_id
					type
					text
					originalFileName
				  }
				  replyTo{
					_id
					text 
					media {
						url
						_id
						type
					  }
					owner {
						nick
					  }
					}
					
					replies{
						_id text 
					}
					forwarded{
						_id
						text
						owner {
							nick
						  }
						  media {
							url
							_id
							type
						  }
					}
					forwardWith{
						_id
						text
					}
				  owner {
					_id
					nick
					avatar {
					  url
					}
				  }
				}
			  }`, {chat: JSON.stringify(
				  	[{"chat._id": _id}, 
						{
                    		sort: [{_id: -1}], limit: [20], skip: [messLen]
						}
					]
				)}
			))
		)
		if(messages){
            
			dispatch(actionAddMessages([...messages], _id))
		}
		return messages
	}