import {Directive, EventEmitter, Injectable, Input, OnChanges, Output} from '@angular/core';
import {UploadAnalysisModel} from '../models/upload.analysis.model';
import {PayInModel} from '../models/pay-in.model';
import {PayInAAARowModel} from '../models/Pay.In.AAA.Row.model';
import {PayInLenderIncomeModel} from './pay-in-lender.income.model';
import {CellCloseEvent} from '@progress/kendo-angular-grid';

@Directive()
export class LenderIncomeAbstractDirective {
  @Input() public analysis = new UploadAnalysisModel({});
  @Input() newPayInUpdate: PayInModel;
  @Output() Selected: EventEmitter<PayInModel> = new EventEmitter<PayInModel>();
  public data: PayInLenderIncomeModel[] = [];
  @Input() payIn: PayInModel[] = [];

  constructor(protected AgencyName: string) {
  }

  OnChanges(changes): void {
    if (changes.newPayInUpdate) {
      const piNew = changes.newPayInUpdate.currentValue as PayInModel;
      this.onNewPayInUpdate(piNew);
    }
    if (changes.payIn){
      this.data.forEach( v => {
        v.matchedPayIn = this.matchPayIn(v);
      });
    }
  }

  private onNewPayInUpdate(piNew: PayInModel): void {
    this.data.forEach(value => {
      const v = value as PayInLenderIncomeModel;
      // remove old matches
      if (v.matchedPayIn !== -1 && v.matchedPayIn.Id === piNew.Id) {
        v.matchedPayIn = -1;
      }

      // add new matches
      if (this.isMatch(v, piNew)) {
        v.matchedPayIn = piNew;
      }
    });
  }

  public onCellClick(event: CellCloseEvent): void{
      this.Selected.emit(event.dataItem.asPayIn());
    }

  protected matchPayIn(v: PayInLenderIncomeModel): PayInModel | -1 {
      const idx = this.payIn.findIndex( pi => this.isMatch(v, pi) );
      if ( idx === -1 ) { return -1; }
      return this.payIn[idx];
  }

  protected isMatch( v: PayInLenderIncomeModel, pi: PayInModel): boolean {
      if ( v === null || pi === null ){
        return false;
      }
      return  v.isMatch(pi);
    }
}
