import { types } from "../actions/actionTypes";
import { SHOPTIME_BASE_URL } from "../api/apiConfig";
import * as Config from "../utils/Config";
import { readLocalStorage, writeLocalStorage } from "../utils/helperMethods";

export const initialLocalSettings = {
  version: 1, // if version changed data will be deleted
  serverType: Config.DEFAULT_SERVERTYPE,
  ricCodeSetting: Config.DEFAULT_RIC_CODE,
  accessToken: null,
  refreshToken: null,
  phoneNumbers: {},
  logEnable: typeof window === "object" && !window.PalmSystem,
  recentItems: [],
  languageSetting: "system", //US, GB, DE, RU
  watchRecord: {},
  oldDb8Deleted: false,
  skipEndOfServicePopup: false,
  preventServerChange: false, // pc 에서 web hotsting 서버에 접속시 서버 변경을 제한한다.
};

const updateAWithBKeys = (A, B) => {
  for (const key in B) {
    if (Object.prototype.hasOwnProperty.call(B, key)) {
      // B에만 존재하는 키를 A에 업데이트
      if (
        !Object.prototype.hasOwnProperty.call(A, key) ||
        A[key] === undefined
      ) {
        A[key] = B[key];
      }
    }
  }
  return A;
};
const updateInitialLocalSettings = () => {
  let data = readLocalStorage("localSettings", initialLocalSettings);

  // pc 에서 web hotsting 서버에 접속시 서버 변경을 제한한다.
  if( typeof window === "object" && !window.PalmSystem && window.location.href.indexOf(SHOPTIME_BASE_URL) > 0){
    data.preventServerChange = true;
    let hrefUrl = window.location.href.split(".")[0];
    if (hrefUrl.indexOf("qt2") >= 0) {
      data.serverType = 'qt2';
    } else if (hrefUrl.indexOf("qt") >= 0) {
      data.serverType = 'qt';
    } else {
      data.serverType = 'prd';
    }
    data.ricCodeSetting = hrefUrl.split("-")[1] ?? hrefUrl.split("//")[1];
    if(data.ricCodeSetting === 'aic'){
      data.languageSetting = 'US';
    }else if(data.ricCodeSetting === 'eic' && (data.languageSetting !== 'GB' && data.languageSetting !== 'DE')){
      data.languageSetting = 'GB';
    }else if(data.ricCodeSetting === 'ruc'){
      data.languageSetting = 'RU';
    }
  }

  if (data.version !== initialLocalSettings.version) {
    console.log(
      "localSettingsReducer version updated. All datas are initialized."
    );
    data = initialLocalSettings;
    writeLocalStorage("localSettings", initialLocalSettings);
  } else {
    updateAWithBKeys(data, initialLocalSettings);
  }
  return data;
};

export const localSettingsReducer = (
  state = updateInitialLocalSettings(),
  action
) => {
  switch (action.type) {
    case types.CHANGE_LOCAL_SETTINGS: {
      const newState = Object.assign({}, state, action.payload);
      writeLocalStorage("localSettings", newState);
      return newState;
    }
    default:
      return state;
  }
};

export default localSettingsReducer;
