import axios from 'axios';

const config = {
  //baseURL: 'http://localhost:7070',
  // baseURL: apiBaseUrl,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
  timeout: 120000, // timeout은 120초로 설정
};

const httpClient = axios.create(config);

const authInterceptor = (config) => {
  // frontend와 backend의 origin이 다른 경우
  // devServer.proxy 설정을 하던지 baseURL과 withCredentials 설정을 해야 한다.
  // cookie, header 등에 자격정보 설정이 필요한 api는 true 설정으로 호출해야 하고
  // 자격정보 설정이 필요없는 api는 withCredentials=false 설정으로 호출해야 한다.
  // config.withCredentials = !config.url.startsWith('/api/public/');
  // console.log("Test Url : "+ config.url);

  /*if(config.url == '/api/auth/login'){
    config.baseURL = "http://localhost:3000";
  }*/
  return config;
};

const tokenInterceptor = (config) => {
  // console.log('http : ',sessionStorage.authToken);
  if (sessionStorage.authToken != null) {
    config.headers.Authorization = 'Bearer ' + sessionStorage.authToken;
  } else if (sessionStorage.authToken == null && sessionStorage.refreshToken != null) {
    config.headers.Authorization = 'Bearer ' + sessionStorage.refreshToken;
  }

  return config;
};

const loggerInterceptor = (config) => {
  //console.log('testProp:', testProp);
  //console.log('request url:', config.url, 'params:', config.data, 'config: ', config);
  return config;
};

let loadOverlap = [];
const loadingLayer = (type, config) => {
  /*
  get: httpClient.get(url, { params: { ... }, headers: {"show-layer": "Yes"} }) // in 2nd property
  post: httpClient.post(url, params, { headers: {"show-layer": "Yes"} })  // 3rd property
  */
  if (type) {
    document.querySelector('html > body').style.overflow = 'hidden'; // 스크롤 block
    document.getElementsByClassName('loadingDimmed')[0].style.display = 'block';
    document.getElementsByClassName('sp-3balls')[0].style.display = 'block';
  } else {
    document.querySelector('html > body').style.removeProperty('overflow'); // 스크롤 allow
    document.getElementsByClassName('loadingDimmed')[0].style.display = 'none';
    document.getElementsByClassName('sp-3balls')[0].style.display = 'none';
  }
};

const urlInterceptor = (config) => {
  if (sessionStorage.fromUrl != null) {
    config.params.fromUrl = sessionStorage.fromUrl;
  }
  return config;
};
const loadingLayerInterceptor = (config) => {
  loadingLayer(true, config);
  return config;
};

/** Adding the request interceptors */
httpClient.interceptors.request.use(authInterceptor);
httpClient.interceptors.request.use(tokenInterceptor);
httpClient.interceptors.request.use(urlInterceptor);
httpClient.interceptors.request.use(loggerInterceptor);
httpClient.interceptors.request.use(loadingLayerInterceptor);

/** Adding the response interceptors */
httpClient.interceptors.response.use(
  (response) => {
    loadingLayer(false, response.config);
    //console.log('response status:', response.status, 'data:', response.data);
    //console.log('response config url :',response.config.url);
    if (response.config.url == '/api/v1/bo/comm/refreshToken') {
      if (response.data.data != null && typeof response.data.data != undefined) {
        sessionStorage.setItem('authToken', response.data.data);
        window.location.reload();
      } else {
        delete sessionStorage.authToken;
        window.top.location.href = '/login';
      }
    }
    return response;
  },
  (error) => {
    console.log(error);
    //alert(error);

    if (error.message === 'Network Error') {
      alert('네트워크 오류가 발생했습니다. 잠시 후 다시 시도해주세요.');
      delete sessionStorage.authToken;
      window.top.location.href = '/login';
    }
    if (error.response != undefined && error.response != null) loadingLayer(false, error.response.config);
    else loadingLayer(false, error.config);

    if (error.code === 'ECONNABORTED') {
      alert('서비스가 지연되고 있습니다. 잠시 후 확인하시고 다시 시도해주세요.');
      return Promise.reject(error);
    } else if (error.response.status == 401) {
      alert('세션이 만료되었습니다.');
      delete sessionStorage.authToken;
      window.top.location.href = '/login';
    } else if (error.response.status == 418) {
      delete sessionStorage.authToken;
      if (error.config.url == '/api/v1/bo/comm/refreshToken') {
        alert('세션이 만료되었습니다.');
        delete sessionStorage.authToken;
        delete sessionStorage.refreshToken;
        return (window.top.location.href = '/login');
        //return Promise.reject(error);
      }
      var params = {};
      httpClient.post('/api/v1/bo/comm/refreshToken', params);
    } else if (error.response.status == 500) {
      window.top.location.href = '/view/error/500';
    }
    // else if (error.message == 'Network Error') {
    //   alert('네트워크 오류가 발생했습니다. 잠시 후 다시 시도해주세요.');
    //   return Promise.reject(error);
    // }
    else {
      delete sessionStorage.authToken;
      console.log('response error:', error);
      return Promise.reject(error);
    }
  }
);

export default httpClient;
