import {appVarActions} from '@configs/appVarReducer';
import {AccountName, XAuthorization, Username} from '@configs/types';
import {saveVarChanges} from '@helper/appData';
import {apiBackendRequest, makeRequest} from '@helper/request';
import BigDataManager from '@helper/storage/BigDataManager';
import {RootState, store} from '@redux/store';
import {useSelector} from 'react-redux';
import {MyUserAccount, createUserProp, SourceProp} from './types';

function createNewMyUser(
  AccountName: AccountName,
  Username: Username,
  SessionId: XAuthorization,
): Promise<void> {
  return new Promise((resolve, reject) => {
    let user: MyUserAccount = {
      AccountName /*: createUserProp(SourceProp.offline, AccountName)*/,
      Username: createUserProp(SourceProp.offline, Username),
      /* Description: createUserProp(SourceProp.online),
      FollowersCount: createUserProp(SourceProp.online),
      FollowingCount: createUserProp(SourceProp.online),
      XpLevel: createUserProp(SourceProp.online),
      XpPoints: createUserProp(SourceProp.online),
      lastUpdateTimestamp: Math.floor(new Date().getTime() / 1000),
      ProfilePicture: {
        lq: createUserProp(SourceProp.online),
      }, */
      SessionId,
      userSettings: {
        lang: store.getState().appVariables.lang.details.langCode,
        theme: store.getState().appVariables.preferences.theme,
      },
    };

    createMyUser(user);
    BigDataManager.initDatabase();

    console.log('appstart');

    makeRequest({
      path: apiBackendRequest.APP_START,
      requestGET: {':AccountName': AccountName},
      response: {
        /*
        AccountName: '',
        Description: '',
        FollowersCount: 0,
        FollowingCount: 0,
        Username: '',
        XpLevel: 0,
        XpPoints: 0,
        AvatarUrl: '',
        AccountStatus: 0,
        Events: {},
        TokenValid: false, */
      },
    })
      .then(resp => {
        let user = {...getMyUser(AccountName)};
        /*
        user.AccountName = createUserProp(
          SourceProp.offline,
          resp.response.AccountName,
        ); 
        user.Username = createUserProp(
          SourceProp.offline,
          resp.response.Username,
        ); 
        user.Description = createUserProp(
          SourceProp.offline,
          resp.response.Description,
        );
        user.FollowersCount = createUserProp(
          SourceProp.offline,
          resp.response.FollowersCount,
        );
        user.FollowingCount = createUserProp(
          SourceProp.offline,
          resp.response.FollowingCount,
        );
        user.XpLevel = createUserProp(
          SourceProp.offline,
          resp.response.XpLevel,
        );
        user.XpPoints = createUserProp(
          SourceProp.offline,
          resp.response.XpPoints,
        );*/

        setMyUser(user);
        resolve();
      })
      .catch(resp => {
        console.error(`appstart req failed: ${resp.status}`);
        reject();
      });
  });
}

function createMyUser(user: MyUserAccount) {
  store.dispatch(appVarActions.setAccount(user));
  store.dispatch(appVarActions.setCurrentAccount(user.AccountName));
  saveVarChanges();
}

function getMyUser(accountName: AccountName): MyUserAccount {
  return store.getState().appVariables.preferences.accounts[accountName];
}

function setMyUser(user: MyUserAccount) {
  store.dispatch(appVarActions.setAccount(user));
  saveVarChanges();
}

function logoutMyUser() {
  store.dispatch(appVarActions.setCurrentAccount('none'));
  saveVarChanges();
}

function getSelectedUserAccount(): AccountName {
  return store.getState().appVariables.preferences.selectedAccount;
}

function getSelectedMyUserSelector(): MyUserAccount | undefined {
  const myUserId = useSelector(
    (state: RootState) => state.appVariables.preferences.selectedAccount,
  );

  const myUser = useSelector(
    (state: RootState) => state.appVariables.preferences.accounts[myUserId],
  );

  return myUser;
}

function getSessionId(accountName?: AccountName): XAuthorization | undefined {
  const preferences = store.getState().appVariables.preferences;

  console.log('pref', preferences);

  let user = preferences.accounts[accountName || preferences.selectedAccount];

  if (user === undefined) return undefined;

  let SessionId = user.SessionId;

  return SessionId;
}

const MyUserManager = {
  createNewMyUser,
  getSessionId,
  getSelectedUserAccount,
  logoutMyUser,
  getSelectedMyUserSelector,
};
export default MyUserManager;
