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

// store.dispatch({
//   type: "PROMISE",
//   name: "login",
//   status: "RESOLVED",
//   payload: "hi",
// });

// store.dispatch({
//   type: "PROMISE",
//   name: "chatList",
//   status: "REJECTED",
//   error: "bye",
// });

// function actionToken(token) {
//   return {
//     type: "TOKEN",
//     token,
//   };
// }

// function actionError(error) {
//   return {
//     type: "ERROR",
//     error,
//   };
// }

// const handleClick = () => history.push("/my_profile")


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())
// .then((a) => {
//   if (a.data.getLogin !== null) {
//     history.push("/my_profile")
//     // handleClick()
//     // window.location.assign("/my_profile")
//   };
// });

const actionLoginPromise =  (login, password) => {
  var promise =  getGQL("http://localhost:3330/graphql")(
    `query l($login:String, $password:String){
        getLogin(login:$login, password:$password)
        }`,
    { login, password }
  )
  return actionPromise("login", promise);
};

// const actionLoginPromise1 =  (login, password) => {
//   var promise =  getGQL("http://localhost:3330/graphql")(
//     `query l($login:String, $password:String){
//         getLogin(login:$login, password:$password)
//         }`,
//     { login, password }
//   )
//   return actionPromise("error", promise);
// };

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

// const mapStateToProps = (comp) => {
//   switch (comp) {
//     case "1":
//       return function (state) {
//         return { a: state.login };
//       };

//     default:
//       return undefined;
//   }
// };

export { actionLogin };
