import axios from "axios";

import * as HelperMethods from "../utils/helperMethods";
import { getUrl, URLS } from "./apiConfig";

// refresh-token 구현 필요
let tokenRefreshing = false;
export const tokenRefresh = (dispatch, getState, autoLogin, callback) => {
  return new Promise((resolve, reject) => {
    // console.log('getState ', getState());
    // const {serverType} = getState().common.localSettings;
    // const url = getUrl(URLS.TOKEN_REFRESH, serverType);
    // const webOSVersionReal = getState().common.appStatus.webOSVersionReal;
    // const {authenticationResult, tokenRequiredTime, userId} = getState().common.localSettings;
    // const deviceId = getState().common.appStatus.deviceId;

    // if(!userId){
    // 	console.warn('tokenRefresh : not logged');
    // 	if(callback){
    // 		callback(false);
    // 	}
    // 	return;
    // }
    // const currentTime = new Date();
    // const gap = (currentTime - tokenRequiredTime)/1000;
    // const ExpiredIn = Number(authenticationResult.ExpiresIn);
    // const limitTime = ExpiredIn - (ExpiredIn * THRESHOLD_AUTH_REFRESH);
    // if(!autoLogin && (gap < limitTime || tokenRefreshing)){
    // 	if(callback){
    // 		callback(false);
    // 	}
    // 	return;
    // }
    // const tokenInfo =
    // {
    // 	"authenticationResult": authenticationResult,
    // 	deviceInfo: {
    // 			"deviceId": deviceId,
    // 			"deviceName": "deviceName01",
    // 			"os": "webos",
    // 			"model": webOSVersionReal,
    // 			"serialNumber": "xxxx-xxxx-xxxx-xxxx"
    // 		}
    // 	, "userId" : userId
    // };
    // if(useQAServerURL !== 'prd'){
    // 	console.log('tokenInfo...', tokenInfo, gap, ExpiredIn);
    // }
    // try{
    // 	tokenRefreshing = true;
    // 	const response = await axios.put(url, tokenInfo, AUTHORIZATION);
    // 	console.log(' tokenRefresh response....', response);
    // 	Actions.AUTHORIZATION.headers.authorization = response.data.authenticationResult.AccessToken;
    // 	dispatch(CommonActions.changeLocalSettings({authenticationResult:response.data.authenticationResult, tokenRequiredTime: new Date()}));
    // 	console.log('토큰 갱신 완료...');
    // 	if(callback){
    // 		callback(true);
    // 	}
    // }catch(res) {
    // 	const error = res && res.toJSON ? res.toJSON() : {};
    // 	console.error('tokenRefresh', error, res);
    // 	if(error.message ){
    // 		if(error.message.indexOf('code 400')
    // 		|| error.message.indexOf('code 401')
    // 		|| error.message.indexOf('code 403')){
    // 			dispatch(Actions.logout());
    // 		}
    // 	}
    // 	if(callback){
    // 		callback(false);
    // 	}
    // };
    tokenRefreshing = false;
    resolve();
  });
};

export const TAxios = (
  dispatch,
  getState,
  type,
  baseUrl,
  urlParams = {},
  params = {},
  onSuccess,
  onFail,
  noTokenRefresh = false
) => {
  const checkAccessToken = () => {
    return new Promise((resolve) => {
      const accessToken = getState().device.accessToken;
      if (
        accessToken ||
        baseUrl === URLS.GET_AUTHENTICATION_CODE ||
        noTokenRefresh
      ) {
        resolve(accessToken);
      } else {
        HelperMethods.wait(100).then(() => {
          resolve(checkAccessToken());
        });
      }
    });
  };

  const executeRequest = (accessToken, getState) => {
    const httpHeader = getState().common.httpHeader;
    const AUTHORIZATION = { headers: {...httpHeader} };

    if (accessToken) {
      AUTHORIZATION.headers["lgsp_auth"] = accessToken;
    }

    if (typeof window === "object") {
      let url = Array.isArray(baseUrl) ? getUrl(getState, baseUrl[0]) : getUrl(getState, baseUrl);

      if(!url){
        //todo error page
        return;
      }
      if (type === "get") {
        const _urlparams = HelperMethods.createQueryString(urlParams);
        url += url ? `?${_urlparams}` : "";
      }

      let axiosInstance;
      switch (type) {
        case "get":
          axiosInstance = axios.get(url, AUTHORIZATION);
          break;
        case "post":
          axiosInstance = axios.post(url, params, AUTHORIZATION);
          break;
        // TODO: 다른 HTTP 메소드 있다면 처리 (chw)
      }

      if (axiosInstance) {
        axiosInstance
          .then((res) => {
            console.log("TAxios response", url, res);
            if (onSuccess) onSuccess(res);
          })
          .catch((error) => {
            console.error("TAxios ", url, error);
            if (onFail) onFail(error);
          });
      }
    }
  };

  checkAccessToken().then((accessToken) => {
    if (!noTokenRefresh) {
      tokenRefresh(dispatch, getState)
        .then(() => executeRequest(accessToken, getState))
        .catch((e) => {
          /* 토큰 갱신 실패 처리 */
          console.error('tokenRefresh error', e);
        });
    } else {
      executeRequest(accessToken, getState);
    }
  });
};
