import getGQL from "../utils/getGQL";
import * as actions from "../constants/actions/index";
import history from "../utils/history";
import { clearTrackList } from "../actions/playerActions";

export function actionLogIn(token) {
  return {
    type: actions.LOGIN,
    token,
  };
}
function actionLogOut() {
  return {
    type: actions.LOGOUT,
  };
}

export const logOut = () => (dispatch) => {
  dispatch(clearTrackList());
  dispatch(actionLogOut());
  history.push("/login");
};

export const doLogin = (login, password) => async (dispatch) => {
  // debugger
  try {
    await getGQL(
      "/graphql"
      // ,{Authorization : "Bearer " + localStorage.authToken}
    )(
      `query Login{
        login(login: "${login}", password: "${password}")
        }`
    ).then((data) => {
      console.log(data);
      // console.log(data.data.login);

      // localStorage.authToken = data.data.login;
      // const token = localStorage.authToken;
      // dispatch(actionLogIn(token));

      dispatch(actionLogIn(data.data.login));
      // const originalFetch = fetch;
      // fetch = (url, params = { headers: {} }) => {
      //   params.headers.Authorization = "Bearer " + localStorage.authToken;
      //   return originalFetch(url, params);
      // };
      // console.log("localStorage.authToken: " + localStorage.authToken);
    });
  } catch (error) {
    console.log(error);
    if (error.message.includes("Invalid token")) {
      alert("Invalid credentials!");
    } else {
      alert("Something went wrong");
    }
  }
};
