import { useDispatch, useSelector } from 'react-redux';
import { fetchMessagesByReceiverId, postNewMessage } from '../../store/features/textMessagesSlice';

export const useMessage = () => {
  const messages = useSelector(state =>
    state.textMessage.messages
      .filter(
        message =>
          (message.senderId === user.id && message.receiverId === window.currentUser.id) ||
          (message.senderId === window.currentUser.id && message.receiverId === user.id)
      )
      .sort((a, b) => {
        return new Date(a.createdAt) - new Date(b.createdAt);
      })
  );

  const fetchMessages = async () => {
    try {
      const options = { userId: user.id, offset: offset, limit: LIMIT };
      setFetching(true);
      await dispatch(fetchMessagesByReceiverId(options)).unwrap();
      if(messages.length < LIMIT){
        goToBottom();
      }
    } catch (err) {
      console.log('ERROR', err);
    } finally {
      setFetching(false);
    }
  };

  const sendMessage = () => {
    let msgData = {
      message: newMessage,
      target_user_id: user.id,
      source_user_id: currentUser.id
    };
    setNewMessage('');

    try {  
      dispatch(postNewMessage(msgData));
    } catch (err) {
      console.log('ERROR', err);
    }
  };

  return { messages, fetchMessages, sendMessage}
}
