import { AsyncStorage } from "react-native";

export class Session {
    saveId = false;
    savedUserId = '';
    autoLogin = false;
    userInfo = null;
    accessToken = null;
    siteId = null;
    loginSite = null;
    menus = null;
    pathMenus = null;
    siteConfig = null;
    /*
    siteConfigMenu = {
      UseWorkAutoOrder: { path : '/Facility/ExecutionSchedule', trueIsShow:false },
      UseWorkAutoResult: { path : '/Facility/WorkWait', trueIsShow:false },
      UseMaterialCode: { path : '', trueIsShow:true },
      UseMaterialBuyAutoAppoval: { path : '', trueIsShow:false },
      UseMaterialStoredAutoApproval: { path : '', trueIsShow:false },
      UseMaterialAdjustmentAutoApproval: { path : '', trueIsShow:false },
      UseMaterialMonlthlyStock: { path : '', trueIsShow:true },
      UseMaterialShortStock: { path : '', trueIsShow:true },
      UseEquipmentRent: { path : '', trueIsShow:true },
      UseEquipmentCurrent: { path : '', trueIsShow:true },
      UsePartnerCode: { path : '', trueIsShow:true },
      UseServicePartner: { path : '', trueIsShow:true },
    };
    */

    logout = async (navigation) => {
      this.saveId = false;
      this.autoLogin = false;
      this.userInfo = null;
      await AsyncStorage.removeItem('user');
      await AsyncStorage.removeItem('access_token');
      navigation.navigate('LoginNavigator');
    };

    load = async () => {
      try {
        const save = await AsyncStorage.getItem('is_save_id');
        if(save) {
          this.saveId = JSON.parse(save);
        }
        this.savedUserId = await AsyncStorage.getItem('saved_user_id');
        const auto = await AsyncStorage.getItem('is_auto_login');
        if(auto) {
          this.autoLogin = JSON.parse(auto);
        }
        this.siteId = await AsyncStorage.getItem('site_id');
        const loginSite = await AsyncStorage.getItem('login_site');
        if(loginSite) {
          this.loginSite = JSON.parse(loginSite);
        }
        this.accessToken = await AsyncStorage.getItem('access_token');
        const user = await AsyncStorage.getItem('user');
        if (user) {
          this.userInfo = JSON.parse(user);
        }
      } catch(error) {
        console.log('session load error', error);
        throw error;
      }
    };
  
    isLoggedIn = () => {
      return this.getUserInfo() ? true : false;
    };
  
    isAdmin = () => {
      return this.getSiteId() == 1 ? true : false;
    };

    isAutoLogin = () => {
      return this.autoLogin;
    };

    setAutoLogin = async (autoLogin) => {
      this.autoLogin = autoLogin;
      await AsyncStorage.setItem('is_auto_login', JSON.stringify(autoLogin));
    };

    isSaveId = () => {
      return this.saveId;
    };

    getSavedUserId = () => {
      return this.savedUserId;
    };

    setIsSaveId = async (saveId, userid) => {
      this.saveId = saveId;
      this.savedUserId = userid;
      await AsyncStorage.setItem('is_save_id', JSON.stringify(saveId));
      await AsyncStorage.setItem('saved_user_id', userid);
    };
  
    getSiteId = () => {
      return this.siteId;
    };
  
    setSiteId = async siteId => {
      this.siteId = siteId+'';
      await AsyncStorage.setItem('site_id', siteId+'');
    };
  
    getLoginSite = () => {
      return this.loginSite;
    };
  
    setLoginSite = async site => {
      this.loginSite = site;
      await AsyncStorage.setItem('login_site', JSON.stringify(site));
    };
  
    getAccessToken = () => {
      return this.accessToken;
    };
  
    setAccessToken = async token => {
      this.accessToken = token;
      await AsyncStorage.setItem('access_token', token);
    };
  
    getUserInfo = (key) => {
      if(typeof key === 'undefined') return this.userInfo;
      if(!this.userInfo) return '';
      return this.userInfo[key];
    };
  
    setUserInfo = async user => {
      this.userInfo = user;
      await AsyncStorage.setItem('user', JSON.stringify(user));
    };

    removeNotAccessMenu = (menus) => {
      // siteconfig menu 중 보이면 안되는 메뉴 Access false 설정
      /*
      for(let menu of menus) {
        for(let sub of menu.children) {
          if(sub.auth != null && sub.auth.Access) {
            for(let key in this.siteConfig) {
              if(typeof this.siteConfigMenu[key] !== 'undefined' && this.siteConfigMenu[key].path && this.siteConfigMenu[key].path == sub.path) {
                if(this.siteConfigMenu[key].trueIsShow && !this.siteConfig[key]) {
                  // true 이면 보이는 메뉴인데 config 값이 false 이면 삭제
                  sub.auth.Access = false;
                }
                if(!this.siteConfigMenu[key].trueIsShow && this.siteConfig[key]) {
                  // false 이면 보이는 메뉴인데 config 값이 true 이면 삭제
                  sub.auth.Access = false;
                }
              }
            }
          }
        }
      }
      */

      // access false 인 메뉴 삭제
      for(var menu of menus) {
        let removeList = [];
        for(let subMenu of menu.children) {
          if(subMenu.auth == null || !subMenu.auth.Access) {
            removeList.push(subMenu);
          }
        }
        for(let remove of removeList) {
          const index = menu.children.indexOf(remove);
          menu.children.splice(index, 1);
        }
      }
      let removeMenuList = [];
      for(let menu of menus) {
        if(typeof menu.children === 'undefined' || menu.children.length == 0) {
          removeMenuList.push(menu);
        }
      }
      for(let remove of removeMenuList) {
        const index = menus.indexOf(remove);
        menus.splice(index, 1);
      }
    };

    saveMenus = async (menus) => {
      this.removeNotAccessMenu(menus);
      await AsyncStorage.setItem('menus', JSON.stringify(menus));
    };

    getPathMenus = () => {
      const allmenus = this.getMenus();
      var pathMenus = {};
      const makePathMenu = (menus, parent=null) => {
        for(let menu of menus) {
          if(typeof menu.path !== 'undefined' && menu.path) {
            menu.parent = parent;
            pathMenus[menu.path] = menu;
          }
          if(typeof menu.children != 'undefined' && menu.children && Array.isArray(menu.children)) {
            makePathMenu(menu.children, menu);
          }
        }
      }
      makePathMenu(allmenus);

      return pathMenus;
    };

    loadMenus = async (force=false) => {
      if(force || !this.menus) {
        this.menus = await AsyncStorage.getItem('menus');
        this.menus = JSON.parse(this.menus);
        this.pathMenus = this.getPathMenus();
      }
      return (this.menus ? this.menus : []);
    };

    getMenus = () => {
      return (this.menus ? this.menus : []);
    };

    getMenu = (path) => {
      if(typeof this.pathMenus[path] === 'undefined') return null;
      else return this.pathMenus[path];
    };

    saveSiteConfig = async (siteConfig) => {
      this.siteConfig = siteConfig;
      await AsyncStorage.setItem('siteConfig', JSON.stringify(siteConfig));
    };

    loadSiteConfig = async () => {
      if(!this.siteConfig) {
        this.siteConfig = await AsyncStorage.getItem('siteConfig');
        this.siteConfig = JSON.parse(this.siteConfig);
      }
      return (this.siteConfig ? this.siteConfig : {});
    };

    getSiteConfig = () => {
      return (this.siteConfig ? this.siteConfig : {});
    };
  }
  
  console.log("================================== new Session ======================================");
  const session = new Session();
  export default session;
  