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) => {
    const AUTHORIZATION = { headers: {} };

    AUTHORIZATION.headers["app_id"] = "com.lgshop.app";
    AUTHORIZATION.headers["app_ver"] = "1.0.0";
    AUTHORIZATION.headers["dvc_id"] = "testdeviceid";
    AUTHORIZATION.headers["cntry_cd"] = "US";
    AUTHORIZATION.headers["prod_cd"] = "webOSTV 5.0";
    AUTHORIZATION.headers["plat_cd"] = "W20H";
    AUTHORIZATION.headers["lang_cd"] = "en-US";
    AUTHORIZATION.headers["os_ver"] = "3.0";
    AUTHORIZATION.headers["sdk_ver"] = "1.0.0";
    AUTHORIZATION.headers["publish_flag"] = "Y";

    // Device Header 임시
    AUTHORIZATION.headers["X-Authentication"] = "MkOLvUocrJ69RH/iV1ZABJhjR2g=";
    AUTHORIZATION.headers["X-Device-ID"] =
      "OemUY5qbPITZv96QKlxrtcqT6ypeX6us2qANLng3/0QCUhv2mecK1UDTMYb/hjpjey9dC/kFycc/5R8u+oK56JIWyYC4V278z64YDPKbDXIsd+eECvyf+Rdm8BneIUPM";
    AUTHORIZATION.headers["X-Device-Product"] = "webOSTV 5.0";
    AUTHORIZATION.headers["X-Device-Platform"] = "W20P";
    AUTHORIZATION.headers["X-Device-Model"] = "HE_DTV_W20P_AFADATAA";
    AUTHORIZATION.headers["X-Device-Eco-Info"] = "1";
    AUTHORIZATION.headers["X-Device-Country"] = "US";
    AUTHORIZATION.headers["X-Device-Language"] = "en-US";
    AUTHORIZATION.headers["X-Device-Netcast-Platform-Version"] = "5.0.0";
    AUTHORIZATION.headers["X-Device-Publish-Flag"] = "N";
    AUTHORIZATION.headers["X-Device-Fck"] = "253";
    AUTHORIZATION.headers["X-Device-Eula"] =
      "additionalDataAllowed,takeOnAllowed,networkAllowed,generalTermsAllowed,chpAllowed,customAdAllowed,acrOnAllowed,voice2Allowed,voiceAllowed,acrAdAllowed";
    AUTHORIZATION.headers["X-Device-Personalization"] = "Y";

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

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

      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))
        .catch(() => {
          /* 토큰 갱신 실패 처리 */
        });
    } else {
      executeRequest(accessToken);
    }
  });
};
