import axios from 'axios';
import SDLUtil from '@/utils/SDLUtil';

const getUserInfo = (formData) => axios.post(`${SDLUtil.API_URL}/noauth/login/id`, formData);
const getNewEpTrayUserInfo = formData => axios.post(`${SDLUtil.API_URL}/noauth/login/new-eptray`, formData);

const setHeaderToken = token => {
  axios.defaults.headers.common['x-auth-token'] = token;
};

export default {
  async login(userId, password) {
    try {
      const formData = new FormData();
      formData.append('userId', userId);
      formData.append('password', password);
      const userInfoResponse = await getUserInfo(formData);
      this.setToken(userInfoResponse.data.jwtToken);

      return Object.assign(userInfoResponse.data, { code: 'authOk' });
    } catch (err) {
      return err.data.error;
    }
  },
  async loginNewEpTray(userInfo, key) {
    try {
      const formData = new FormData();
      formData.append('encodeUserInfo', userInfo);
      formData.append('encodeAesKey', key);
      const userInfoResponse = await getNewEpTrayUserInfo(formData);
      this.setToken(userInfoResponse.data.jwtToken);

      return Object.assign(userInfoResponse.data, { code: 'authOk' });
    } catch (err) {
      // console.error('login:', err);
      return err.data.error;
    }
  },
  logout() {
    this.setToken('');
  },
  setToken(token) {
    if (token === '' || token === null) {
      // impersonator check
      if (localStorage.getItem('adminToken') !== null && localStorage.getItem('adminToken') !== '') {
        // call axios
        axios.put(`${SDLUtil.API_URL}/impersonation/logout`).then(() => {});
        this.setToken(localStorage.getItem('adminToken'));
        localStorage.setItem('adminToken', '');
        axios.defaults.headers.common['original-user-id'] = '';
        document.location = `${SDLUtil.WEB_CONTEXT_PATH}/`;
      } else {
        setHeaderToken('');
        localStorage.setItem('user', '');
        localStorage.setItem('userToken', '');
      }
    } else {
      setHeaderToken(token);
      localStorage.setItem('userToken', `${token}`);
      localStorage.setItem('user', JSON.stringify(SDLUtil.parseJwt(token)));

      const defaultLang = (window.navigator.userLanguage || window.navigator.language || SDLUtil.DEFAULT_LANG).replace('-', '_');
      SDLUtil.setI18nLanguage(SDLUtil.getLoginedUserInfo().language || defaultLang); // Change to language setting of login user
    }
  },
};
