// ** UseJWT import to get config
import axios from "axios";
import {isUserLoggedIn} from "../utils/Utils";
import jwtApplicationConfig from "auth/jwtApplicationConfig";
import jwt_decode from "jwt-decode";

//import axios from "axios";
export const refreshIntervalName = 'refreshInterval'
export const predictProductionQty = 'predictProductionQty'
export const predictUsageCount = 'predictUsageCount'
export const windowCount = 'windowCount'

// ** Handle User Login
export const handleLogin = data => {
    return dispatch => {

        dispatch({
            type: 'LOGIN',
            data,
            jwtApplicationConfig,
            accessToken: data['accessToken'],
            refreshToken: data['refreshToken']
        })

        console.log(data)
        // ** Add to user, accessToken & refreshToken to localStorage
        localStorage.setItem('userData', JSON.stringify(data))
        localStorage.setItem('accessToken', data.accessToken)
        localStorage.setItem('refreshToken', data.refreshToken)
        localStorage.setItem('axiosToken', "Bearer " + data.accessToken)
        //localStorage.setItem(config.storageUserRoleKeyName, JSON.stringify(data.role).slice(1).slice(0, -1))
        localStorage.setItem(refreshIntervalName, "60")
        // for demo only
        localStorage.setItem(windowCount, '0')
        localStorage.setItem(predictProductionQty, '0')
        localStorage.setItem(predictUsageCount, '0')
    }
}

export const isTokenValid = () =>{
    let isExpired = false;
    const token = localStorage.getItem('accessToken');
    let decodedToken=jwt_decode(token);
    let dateNow = new Date();
   
    if(decodedToken.exp < dateNow.getTime())
    isExpired = true;
    return isExpired;
   }

// ** Handle User Logout
export const handleLogoutFunction = () => {
    return dispatch => {
        dispatch({
                type: 'LOGOUT',
                accessToken: null,
                refreshToken: null
            }
        )

        console.log("logout");
        // ** Remove user, accessToken & refreshToken from localStorage
        localStorage.removeItem('userData')
        localStorage.removeItem('accessToken')
        localStorage.removeItem('refreshToken')
        //localStorage.removeItem(config.storageUserRoleKeyName)
        localStorage.removeItem(refreshIntervalName)
        localStorage.removeItem(windowCount)
        localStorage.removeItem(predictProductionQty)
        localStorage.removeItem(predictUsageCount)

    }
}

// ** Handle axios token
export const setupAxiosInterceptors = () => {
    axios.interceptors.request.use(
        config => {
            // ** Get token from localStorage
            const accessToken = localStorage.getItem("accessToken")

            // ** If token is present add it to request's Authorization Header
            if (isUserLoggedIn()) {
                config.headers.Authorization = `${jwtApplicationConfig.tokenType} ${accessToken}`
            }
            config.headers['X-Authorization'] = process.env.REACT_APP_API_KEY

            return config
        },
        error => Promise.reject(error)
    )
}
