import { GlobalLoaderService } from './../../resources/global-loader/global-loader-service';
import { DataFormat } from 'select2';
import { I18N } from 'aurelia-i18n';
import { Container, autoinject, TaskQueue, computedFrom } from 'aurelia-framework';
import { ImportRow, ImportRowError, ImportService, ImportSession } from '../service/import-service';
import { DisplayContext } from '../import-data-index';
import { FloatingBoxViewModel } from '../../modules/dialogs/floating-box';



@autoinject
export class ImportCorrectErrors extends FloatingBoxViewModel {

  selectedErrors: Array<ImportRow> = [];
  isUnit: boolean = false;
  importedRows: ImportRow[];
  oldValueString: string;
  valueSelected: DataFormat;
  saveNewAlias: boolean;
  displayContext: DisplayContext = 'errorsFix';
  uiTableVM: any;
  i18n: I18N;
  serverError: ImportRowError;

  constructor(private session: ImportSession,
    private fieldName: string,
    private line: ImportRow,
    private globalLoaderService: GlobalLoaderService,
    private importService: ImportService,
    private errorTableView: string,
    private initRows: ImportRow[]) {
    super("./import-correct-errors.html", "lg");
    this.i18n = Container.instance.get(I18N);
  }

  async activate(config) {
    super.activate(config);
    this.saveNewAlias = false;
    this.serverError = this.line.serverErrors.find(x => x.propertyName.toLowerCase() == this.fieldName.toLowerCase());
    if (this.serverError != null) {
      this.oldValueString = this.serverError.errorValue;
      this.valueSelected = { id: this.line[this.fieldName], text: this.line[this.fieldName] }
    }

    await this.filterCurrentErrorLines(true);

  }
  filter(data: ImportRow) {
    return true;
  }

  @computedFrom('currentPriceOfferLines.length')
  public get title(): string {
    return this.importedRows?.filter(x => x.id != this.line.id).length + ' ' + this.i18n.tr('importdata.similarErrors');
  }
  public async apply(): Promise<void> {
    let ids = this.selectedErrors.map(x => x.id);
    ids.push(this.line.id);
    const batchResults = await this.importService.saveImportRowBatch(this.session.contextName, this.session.id, ids, this.fieldName, this.line[this.fieldName], this.saveNewAlias, this.oldValueString)

    batchResults.forEach(updatedRow => {
      const existingRow = this.initRows.find(x => x.id == updatedRow.id);
      existingRow.isValid = updatedRow.isValid;
      existingRow[this.fieldName] = updatedRow[this.fieldName];
      if (existingRow.serverErrors == null) {
        existingRow.serverErrors = [];
      }
      else {
        existingRow.serverErrors.splice(0);
      }
      existingRow.serverErrors.push(...updatedRow.serverErrors);

    });
    this.filterCurrentErrorLines(true);
    this.uiTableVM.filterChanged();
  }

  private async filterCurrentErrorLines(autoClose: boolean = true) {
    if (this.importedRows == null) {
      this.importedRows = [];
    }
    this.importedRows.splice(0);
    this.importedRows.push(...this.initRows.filter(x => x != null && x[this.fieldName] == this.oldValueString && x.id != this.line.id));

    if (autoClose && this.importedRows.length == 0) {
      if (this.dialogController != null) {
        this.dialogController.close(true);
        await super.close();
      } else {
        let taskQueue = Container.instance.get(TaskQueue);
        taskQueue.queueTask(async () => {
          await super.close();
        })
      }
    }
    if (this.selectedErrors == null) {
      this.selectedErrors = new Array();
    }
    this.selectedErrors.splice(0);
    this.selectedErrors.push(...this.importedRows);
  }
}
