import { MainStateManager } from '../MainStateManager';
import { ModelLogin } from './ModelLogin';
import { TabPageData } from '../Page/Tab/TabData';
import { IData } from '../Data';
import { SelfMobileNumber } from '../SelfModels/SelfMobileNumber';
import { SelfNumber } from '../SelfModels/SelfNumber';
import { SelfString } from '../SelfModels/SelfString';
import { SelfCheckTree } from '../SelfModels/SelfCheckTree';

interface IResult {
  userName: string;
  password: string;
  languageId: number;
  mobileNumber: string;
  captcha: string;
}

interface IRegister {
  codeSMS: string;
}

interface IObjectAuthentication {
  mobileNumber: string;
  captchaCode: string;
  sessionId: string;
}

interface ILogin {
  userName: SelfString;
  password: SelfString;
  rememberMe: SelfCheckTree;
  mobileNumber: SelfMobileNumber;
  captchaCode: SelfNumber;
  codeSMS: SelfNumber;
  result: IResult;
}
interface ILoginResponse {
  isSuccess: boolean;
  data: {
    id: number;
    roles: string[];
    accessToken: string;
    userName: string;
    firstName: string;
    lastName: string;
    smallPicture: string;
    picture: string;
    attachedData: IData[];
  };
  message: string;
}

interface IResponse {
  isSuccess: boolean;
  messageRoot: string;
  data: any;
}

export type StateType = 'none' | 'loading' | 'error' | 'invalid';

export class Login extends ModelLogin {
  public loadingState: StateType = 'none';
  public imageOfcaptcha: string = '';
  public imageOfCaptchaLoadingState: 'loading' | 'loaded' | 'error' = 'loading';
  public sessionId: string = '';
  public timer: boolean = false;
  public initializeListener: boolean = false;
  public initializeVerifyListener: boolean = false;
  public messageRoot?: 'UserNameOrPasswordIsNotValid' | 'MobileNumberIsNotValid' | 'CaptchaCodeIsNotValid' | 'AuthenticationCodeExpired' | 'AuthenticationCodeIsNotValid';
  public pageData = new TabPageData(this.mainStateManager);

  startToAccepting = (): void => { };

  afterSaveSuccessed = (data: ILoginResponse) => { };

  #mobileNumber = SelfMobileNumber.empty();
  public get mobileNumber(): SelfMobileNumber {
    return this.#mobileNumber;
  }
  setMobileNumber = (e: SelfMobileNumber) => {
    this.userName.setValue(e.value);
  };

  #captchaCode = SelfNumber.empty();
  public get captchaCode(): SelfNumber {
    return this.#captchaCode;
  }
  public set captchaCode(value: SelfNumber) {
    this.#captchaCode = value;
  }
  setCaptchaCode = (e: string) => { };

  #codeSMS = SelfNumber.empty();
  public get codeSMS(): SelfNumber {
    return this.#codeSMS;
  };
  setCodeSMS = (e: string) => { };

  #userName = SelfString.empty();
  get userName(): SelfString {
    return this.#userName;
  }
  setUserName = (e: SelfString) => {
  };

  #firstName = SelfString.empty();
  get firstName(): SelfString {
    return this.#firstName;
  }
  setFirstName = (e: SelfString) => {
  };

  #lastName = SelfString.empty();
  get lastName(): SelfString {
    return this.#lastName;
  }
  setLastName = (e: SelfString) => {
  };

  #password = SelfString.empty();
  get password(): SelfString {
    return this.#password;
  }
  setPasswor = (e: SelfString) => { };


  #verifyPassword = SelfString.empty();
  get verifyPassword(): SelfString {
    return this.#verifyPassword;
  }
  setVerifyPassword = (e: SelfString) => { };

  public isPasswordsMatch = () => {
    return this.#password.value === this.#verifyPassword.value;
  }

  get languageId(): number {
    return 0;
    // return this.mainStateManager.Languaging.Current.id;
  }
  setLanguageId = (e: number) => { };

  #rememberMe = SelfCheckTree.empty();
  get rememberMe(): SelfCheckTree {
    return this.#rememberMe;
  }
  setRememberMe = (e: SelfCheckTree) => { };

  public get result() {
    return {
      userName: this.#userName.value,
      password: this.password.value,
      languageId: this.languageId,
      mobileNumber: this.#mobileNumber.value,
      captcha: this.captchaCode.value
    }
  }

  // getAuthenticationCode = () => {
  //   this.loadingState = 'loading';
  //   this.trigger('change');

  //   if (this.mobileNumber.validation instanceof Array) {
  //     this.loadingState = 'none';
  //     this.messageRoot = 'MobileNumberIsNotValid';
  //     this.trigger('change');
  //   } else if (this.captchaCode.validation instanceof Array) {
  //     this.loadingState = 'none';
  //     this.messageRoot = 'CaptchaCodeIsNotValid';
  //     this.trigger('change');
  //   } else {
  //     const data: IObjectAuthentication = { mobileNumber: this.mobileNumber.value, captchaCode: this.captchaCode.value.toString(), sessionId: this.sessionId };
  //     this.postWithoutToken<any, any>('sms', 'GetAuthenticationCode', data)
  //       .then(response => {
  //         if (response.isSuccess) {
  //           this.timer = true;
  //           this.mainStateManager.Usering.userLoginFormState = 'verify';
  //           this.loadingState = 'none';
  //           this.messageRoot = undefined;
  //           this.trigger('change');
  //         } else {
  //           this.getCaptchaImage();
  //           this.#captchaCode.setValue(null);
  //           this.loadingState = 'error';
  //           this.messageRoot = response.messageRoot;
  //           this.trigger('change');
  //         }
  //       })
  //       .catch(error => {
  //         this.loadingState = 'error'
  //         this.trigger('change');
  //       })
  //       ;

  //     this.trigger('change');
  //   }

  // }

  // getCaptchaImage = () => {
  //   this.triggerControl('change', 'captcha');

  //   this.get<any, undefined>('sms', 'GetCaptcha')
  //     .then(response => {
  //       if (response.isSuccess) {
  //         this.imageOfCaptchaLoadingState = "loaded";
  //         this.imageOfcaptcha = 'data:image/png;base64,' + response.data.captcha;
  //         this.sessionId = response.data.sessionId;
  //         this.triggerControl('change', 'captcha');
  //       } else {
  //         this.imageOfCaptchaLoadingState = "error";
  //         this.triggerControl('change', 'captcha');
  //       }
  //     })
  //     .catch(error => {
  //       this.imageOfCaptchaLoadingState = "error";
  //       this.triggerControl('change', 'captcha');
  //     });
  // }

  // backToLoginForm = () => {
  //   this.loadingState = 'none';
  //   this.mainStateManager.Usering.userLoginFormState = 'login';
  //   this.trigger('change');
  // }

  // Register = () => {
  //   this.loadingState = 'loading';
  //   this.trigger('change');

  //   this.postWithoutToken<any, any>('sms', 'Register', {
  //     userName: this.userName.value,
  //     password: this.password.value,
  //     firstName: this.firstName.value,
  //     lastName: this.lastName.value,
  //     mobileNumber: this.mobileNumber.value,
  //     authenticationCode: this.codeSMS.value.toString()
  //   }).then(response => {
  //     this.timer = false;
  //     if (response.isSuccess) {
  //       this.loadingState = 'none';
  //       this.mainStateManager.Usering.userLoginFormState = 'MobileRegistered';
  //       this.userName.setValue(this.mobileNumber.value);
  //       this.password.setValue(this.mobileNumber.value);
  //       this.messageRoot = undefined;
  //       this.trigger('change');
  //     } else {
  //       this.loadingState = 'error';
  //       this.messageRoot = response.messageRoot;
  //       this.captchaCode.setValue(null);
  //       this.mainStateManager.Usering.userLoginFormState = 'signup';
  //       this.trigger('change');
  //     }
  //   }).catch(error => {
  //     this.timer = false;
  //     this.loadingState = 'error';
  //     this.trigger('change');
  //   });
  // }

  // startToLogin = () => {
  //   this.loadingState = 'loading';
  //   this.trigger('change');

  //   this.postWithoutToken<{ sessionId: string, captchaCode: string, userName: string, password: string, languageId: number }, IResponse>('user', 'Login', {
  //     sessionId: this.sessionId,
  //     captchaCode: this.captchaCode.value ? this.captchaCode.value.toString() : '',
  //     userName: this.userName.value,
  //     password: this.password.value,
  //     languageId: this.languageId
  //   })
  //     .then(response => {
  //       this.loadingState = 'none';
  //       if (response.isSuccess) {
  //         this.mainStateManager.Usering.userLogin(response.data, this.rememberMe.value === 0 ? false : true);
  //       } else {
  //         // if (this.mainStateManager.isAmisa) {
  //         //   this.captchaCode.setValue(null);
  //         //   this.getCaptchaImage();
  //         // }
  //         this.loadingState = 'error';
  //         this.messageRoot = response.messageRoot as any;
  //         this.trigger('change');
  //       }
  //     })
  //     .then(error => {
  //       this.loadingState = 'error';
  //       this.trigger('message.InvalidArgument', error);
  //     });
  // };

  // startToChangeDataBase = (attachedDataId: number, financialPeriodId: number, setToActive: boolean) => {

  //   this.post<{ attachedDataId: number, financialPeriodId: number, setToActive: boolean }, any>('user', 'newToken', { attachedDataId, financialPeriodId, setToActive })
  //     .then(response => {
  //       if (response.isSuccess) {
  //         this.mainStateManager.Usering.userChangeData(response.data);
  //       } else {
  //         this.mainStateManager.Eventing.trigger('error', response.messageRoot);
  //       }
  //     })
  //     .catch(error => { })
  // };

  static empty(): ILogin {
    return {
      userName: SelfString.empty(),
      password: SelfString.empty(),
      rememberMe: SelfCheckTree.empty(),
      captchaCode: SelfNumber.empty(),
      codeSMS: SelfNumber.empty(),
      mobileNumber: SelfMobileNumber.empty(),
      result: {
        userName: '',
        password: '',
        languageId: 0,
        captcha: '',
        mobileNumber: '',
      },
    };
  }

  static buildNew(mainStateManager: MainStateManager): Login {
    return new Login(mainStateManager);
  }
}
