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

@ObservedV2
export class TakeMaterialViewModel extends BaseViewModel {
  @Trace materialInfo?: MaterialInfoEntity;
  @Trace analysisInfo?: MaterialInfoEntity;
  @Trace permissionInfo?: VipPermissionEntity;
  @Trace errorCode: number = 0;

  private intervalId = 0

  async getMaterialInfo(content: string) {
    this.showLoading();
    try {
      const result = await apiService.getMaterialInfo(content);
      if (result.isSuccess()) {
        this.materialInfo = plainToInstance(MaterialInfoEntity, result.data);
      } else {
        this.errorCode = result.code
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async analysisMaterial(logId: string, timeout: number) {
    this.cancelInterval()
    try {
      let count = timeout;
      this.intervalId = setInterval(async () => {
        if (count > 0) {
          count--;
          const result = await apiService.analysisMaterial(logId);
          if (result.isSuccess()) {
            this.analysisInfo = plainToInstance(MaterialInfoEntity, result.data);
            if (this.analysisInfo.material !== null || this.analysisInfo.status === -2) {
              this.cancelInterval()
            }
          } else {
            this.errorCode = result.code
            ToastUtils.show(result.message, true);
            this.cancelInterval()
          }
        } else {
          this.cancelInterval()
        }
      }, 1000)
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.cancelInterval()
    }
  }

  async reportStatus(logId: string, status: string, size: string = '', message: string = '') {
    try {
      apiService.reportDownLoadStatus(logId, status, size, message)
    } catch (e) {
      console.log(e);
    }
  }

  async checkVip() {
    this.showLoading();
    try {
      const result = await apiService.checkPermission('download');
      if (result.isSuccess()) {
        this.permissionInfo = plainToInstance(VipPermissionEntity, result.data);
      } else {
        this.errorCode = result.code
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading()
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  cancelInterval() {
    if (this.intervalId !== 0) {
      clearInterval(this.intervalId)
    }
  }
}