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

@ObservedV2
export class DownloadHistoryViewModel extends BaseViewModel {
  @Trace getHistory?: Array<DownloadHistoryEntity>;
  @Trace deleteHistory?: object;

  async getHistoryList(page: string = '1', startTime: string, endTime: string) {
    this.showLoading();
    try {
      const result = await apiService.getDownloadHistoryList(page, startTime, endTime);
      if (result.isSuccess()) {
        this.getHistory = plainToInstance(DownloadHistoryEntity, result.data!!['items'] as Array<Object>);
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async deleteHistoryList(startTime: string, endTime: string) {
    this.showLoading();
    try {
      const result = await apiService.deleteDownloadHistory(startTime, endTime);
      if (result.isSuccess()) {
        this.deleteHistory = new Object();
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }
}