import {appVarActions} from '@configs/appVarReducer';
import {
  AccountName,
  EMail,
  XAuthorization,
  UserId,
  Username,
  WebSocketSessionId,
} from '@configs/types';
import {saveVarChanges} from '@helper/appData';
import {apiBackendRequest, makeRequest} from '@helper/request';
import {store} from '@redux/store';
import {MyUserAccount, createUserProp, SourceProp} from './types';

function createNewMyUser(
  UserId: UserId,
  AccountName: AccountName,
  Username: Username,
  EMail: EMail,
  SessionId: XAuthorization,
  WebSocketSessionId: WebSocketSessionId,
): Promise<void> {
  return new Promise((resolve, reject) => {
    let user: MyUserAccount = {
      UserId,
      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),
      EMail,
      SessionId,
      WebSocketSessionId,
      lastUpdateTimestamp: createUserProp(
        SourceProp.offline,
        Math.floor(new Date().getTime() / 1000),
      ),
      ProfilePicture: {
        hq: createUserProp(SourceProp.offline),
        lq: createUserProp(SourceProp.offline),
      },
      userSettings: {
        lang: store.getState().appVariables.lang.details.langCode,
        theme: store.getState().appVariables.preferences.theme,
      },
    };

    console.log('SessionId', SessionId);

    createMyUser(user);

    makeRequest({
      path: apiBackendRequest.APP_START,
      requestGET: {':userId': UserId},
      response: {
        AccountName: '',
        Description: '',
        FollowersCount: 0,
        FollowingCount: 0,
        Username: '',
        XpLevel: 0,
        XpPoints: 0,
        AvatarUrl: '',
        AccountStatus: 0,
        Events: {},
        TokenValid: false,
      },
    })
      .then(resp => {
        let user = {...getMyUser(UserId)};
        console.log(user);
        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(resp.status);
        reject();
      });
  });
}

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

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

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

function getSessionId(userId?: UserId): XAuthorization | undefined {
  const preferences = store.getState().appVariables.preferences;
  let user = preferences.accounts[userId || preferences.selectedAccount];

  if (user === undefined) return undefined;

  let SessionId = user.SessionId;

  console.log(userId || preferences.selectedAccount);
  console.log(preferences.accounts[userId || preferences.selectedAccount]);

  return SessionId;
}

const MyUserManager = {createNewMyUser, getSessionId};
export default MyUserManager;
