import { actionPromise, store } from "../../../store/store";
// import history from '../../history';

const getGQL = (url, headers = {}) => (query = "", variables = {}) =>
  fetch(url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      ...headers,
    },
    body: JSON.stringify({ query, variables }),
  }).then((res) => res.json());

const actionChatGroupPromise = (id) => {
  var promise = getGQL("http://localhost:3330/graphql")(
    `query allMessOneUser($id: ID!){
      getAllChatGroupsOneUser(id: $id){
        id, autorId{
          id, login
        }, partnerId {
          id, login
        }
      }
    }`,
    { id }
  );
  return actionPromise("chatGroup", promise);
};

const actionChatGroup = (id) => {
  return async (dispatch) => {
    var token = await dispatch(actionChatGroupPromise(id));
    // console.log(token);
    // if (token === undefined) await dispatch(actionLoginPromise1(login, password))
    // if(token) history.push("/my_profile")
  };
};

const actionMessagePromise = () => {
  var promise = getGQL("http://localhost:3330/graphql")(
    `query allMessage{
      getAllMessages {
        id, message, autorId {
          id, login
        }, partnerId {
          id, login
        }
      }
    }`
  );
  return actionPromise("message", promise);
};

const actionMessage = () => {
  return async (dispatch) => {
    var token = await dispatch(actionMessagePromise());
    // console.log(token);
  };
};

const actionUsersPromise = (email) => {
  var promise = getGQL("http://localhost:3330/graphql")(
    `query find($email: String) {
      getUser(email: $email) {
        id, email, login
      }
    }`,
    { email }
  );
  return actionPromise("users", promise);
};

const actionUsers = (email) => {
  return async (dispatch) => {
    var token = await dispatch(actionUsersPromise(email));
    // console.log(token);
  };
};

const actionAllMessOneUserPromise = (id) => {
  var promise = getGQL("http://localhost:3330/graphql")(
    `query allMessOneUser($id: ID!){
      getAllMessagesOneUser(id:$id){
        id, message, autorId{
          id, login
        }, partnerId{
          id, login
        }
      }
    }`,
    { id }
  );
  return actionPromise("allMessOneUser", promise);
};

const actionAllMessOneUser = (id) => {
  return async (dispatch) => {
    var token = await dispatch(actionAllMessOneUserPromise(id));
    // console.log(token);
  };
};

export { actionChatGroup, actionMessage, actionUsers, actionAllMessOneUser };
