// import { gql} from "../utils/getGQL";
import { getGQL } from "../utils/getGQL";
import React, { useEffect, useState } from "react";
import * as actions from "../constants/actions/index";
import history from "../utils/history";
import { clearTrackList } from "../actions/playerActions";
import { getTracks } from "./playerActions";
import RegisterForm from '../components/RegisterForm';

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

export const logOut = () => (dispatch) => {
  dispatch(clearTrackList());
  dispatch(actionLogOut());
};

// export let url = "/graphql";
// export let headers = {
//   Authorization: "Bearer " + localStorage.authToken,
//   // Authorization: `Bearer ${localStorage.authToken}`,
// };

// export let l; 

export const doLogin = (login, password) => async (dispatch) => {
  try {
    localStorage.authToken = "";
    localStorage.id = "";
    let response = await getGQL("/graphql", {
      Authorization: `Bearer ${localStorage.authToken}`,
    })(
      // let response = await gql(
      `query Login($login:String!, $password:String!){
        login(login:$login, password:$password)
        }`,
      {
        login,
        password,
      }
    );
    // .then((data) => {
    //   console.log(data)
    // return
    console.log(response);
    await dispatch(actionLogIn(response.data.login));
    localStorage.user = login;
    // l = login;
    // console.log(l)
  } catch (error) {
    console.log(error);
    if (error.message.includes("Invalid token")) {
      alert("Invalid credentials!");
    } else {
      alert("Something went wrong");
      console.log(error);
    }
  }
};



export const newUser = (login, password) => 
async (dispatch) => {
  // localStorage.authToken = "";
  let response = await getGQL("/graphql",      
  )(
      `mutation User{
      createUser (login: "${login}", password: "${password}"){
      _id login
        }
    }`
  )
  // .then((response) => {
    // console.log(response);
    console.log(response.data.createUser);

    // response.data.createUser !== null? await dispatch(actionNewUser(response.data.createUser)) : alert(`User ${login} has already been created. Please use another login`)
    response.data.createUser !== null? await dispatch(doLogin(response.data.createUser.login, password)) : alert(`User ${login} has already been created. Please use another login`)

    // useEffect( doLogin && doLogin(login, password), []);
    // console.log('localStorage.authTocken: ',localStorage.authTocken);
    // if (!response.errors && login && password) {
    //   useEffect(doLogin(login, password), [])
    //   doLogin && doLogin(login, password)? history.push("/private"): alert('Do not correct doLogin use');
    // } else {
    // }
  // });
};

export const actionNewUser = ({login, _id}) => ({
  type: actions.NEW_USER,
  login, 
  _id
})

// console.log(actionNewUser)