import React, { useState, Component } from "react";
import { connect } from "react-redux";

import { actionMessage } from "./actionMessages/actionMessages";
import "./chatMessages.css";

const Messages = ({ id, login, message, autor, partner }) => {
  localStorage.setItem("login", login);
  
  return (
    <div className="messages">
      <div className="messageAutor">
        {+localStorage.getItem("id") === autor.id ? message : null}
      </div>

      <div className="messagePartner">
        {+localStorage.getItem("id") === partner.id ? message : null}
      </div>
    </div>
  );
};

class ChatMessageInfo extends Component {
  way(obj, resolverName, a) {
    const stateObj = this.props.state[obj];
    for (var keys in stateObj) {
      for (var keyData in stateObj[keys]) {
        if (keyData === "data") {
          const allObj = stateObj[keys][keyData][resolverName];
          if (allObj) return allObj.map(a);
        }
      }
    }
  }

  render() {
    return (
      <>
        <div className="loginPartner">{localStorage.getItem("login")}</div>
        <div className="chatMessages">
          <div className="messagesBlock">
            {this.way("message", "getAllMessages", (el) => (
              <Messages
                key={el.id}
                id={
                  +localStorage.getItem("id") !== el.autorId.id
                    ? el.autorId.id
                    : el.partnerId.id
                }
                message={el.message}
                autor={el.autorId}
                partner={el.partnerId}
                login={
                  +localStorage.getItem("id") !== el.autorId.id
                    ? el.autorId.login
                    : el.partnerId.login
                }
              />
            ))}
          </div>

          <div className="sendMessage">
            <input />
            <button>Send</button>
          </div>
        </div>
      </>
    );
  }
}

const ChatMessage = () => <ConnectedChatMessage />;

const ConnectedChatMessage = connect(
  (state) => {
    return { state };
  },
  { message: actionMessage }
)(ChatMessageInfo);

export default ChatMessage;
