import {Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output} from '@angular/core';
import {UploadAnalysisModel} from '../../models/upload.analysis.model';
import {CellCloseEvent} from '@progress/kendo-angular-grid';
import {PayInAAARowModel} from '../../models/Pay.In.AAA.Row.model';
import {PayInModel} from '../../models/pay-in.model';
import {Subject} from 'rxjs';


@Component({
  selector: 'app-lender-aaa-income',
  templateUrl: './lender-aaa-income.component.html',
  styleUrls: ['./lender-aaa-income.component.scss']
})
export class LenderAaaIncomeComponent implements OnInit, OnChanges {
  private Lender = 'AAA';
  @Input() public analysis = new UploadAnalysisModel({});
  @Input() newPayInUpdate: PayInModel;
  @Output() Selected: EventEmitter<PayInModel> = new EventEmitter<PayInModel>();
  public data: PayInAAARowModel[] = [];
  private payInCandidates: PayInModel[] = [];
  constructor() { }

  ngOnInit(): void {
    this.analysis.AAA.forEach(v => {
      v.matchedPayIn = this.matchPayIn(v);
      this.data.push(new PayInAAARowModel(v));
      v.InTrail = 20;
      this.data.push(new PayInAAARowModel(v));
    });
    console.log(this);
  }

  ngOnChanges(changes): void {
    if (changes.newPayInUpdate){
      this.data.forEach(v => {
        if ( this.isMatch(v, changes.newPayInUpdate.currentValue) ){
          v.matchedPayIn = changes.newPayInUpdate.currentValue;
        }
      });
    }
  }

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

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

  private isMatch( v: PayInAAARowModel, pi: PayInModel): boolean {
    if ( v === null || pi === null ){
        return false;
    }
    return  v.LoanNumber === pi.LoanNumber &&
      this.Lender === pi.Lender &&
      v.InTrail === pi.IncomeAmount &&
      'Trail' === pi.IncomeType;
  }

  @Input() set payIn(pis: PayInModel[]) {
    this.payInCandidates = [];
    pis.forEach( v => this.payInCandidates.push(new PayInModel(v)));

    this.data.forEach( v => {
      v.matchedPayIn = this.matchPayIn(v);
    });

    console.log ('new payin comes in');
  }

  get PayIn(): PayInModel[] {
    return this.payInCandidates;
  }
}
