import { plainToInstance } from 'class-transformer';
import { AccountEntity } from '../entity/AccountEntity';
import { LoginEntity } from '../entity/LoginEntity';
import { apiService } from '../net/ApiService';
import { ToastUtils } from '../utils/ToastUtils';
import { BaseViewModel } from './BaseViewModel';

@ObservedV2
export default class ManageAccountViewModel extends BaseViewModel {
  @Trace accounts?: Array<AccountEntity>;
  @Trace loginEntity?: LoginEntity;

  async accountList() {
    this.showLoading();
    try {
      const result = await apiService.accountList('account');
      if (result.isSuccess()) {
       this.accounts = plainToInstance(AccountEntity, result.data as Array<Object>);
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async changeAccount(userId: string) {
    this.showLoading();
    try {
      const result = await apiService.changeAccount(userId)
      if (result.isSuccess()) {
        this.loginEntity = plainToInstance(LoginEntity, result.data);
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }
}