import {PayInModel} from './pay-in.model';
import {PayInLenderIncomeModel} from '../abstract/pay-in-lender.income.model';

export class PayInConnectiveModel extends PayInLenderIncomeModel {
  public Period: Date;
  public LoanAccount: string;
  public Name: string;
  public Settled: Date;
  public Lender: string;
  public LoanAmount: number;
  public Balance: number;
  public Associate: string;
  public Comm: number;
  public Type: string;
  public Percent: number;
  public Paid: number;
  public GST: number;
  public Total: number;


  constructor(payload: Partial<PayInConnectiveModel>){
    super('Connective', payload);
    this.Period = new Date(payload.Period);
    this.LoanAccount = payload.LoanAccount || '';
    this.Name = payload.Name || '';
    this.Settled = new Date(payload.Settled);
    this.Lender = payload.Lender || '';
    this.ensureLenderHasAgencyNameAppended();
    this.LoanAmount = payload.LoanAmount || 0;
    this.Balance = payload.Balance || 0;
    this.Associate = payload.Associate || '';
    this.Comm = payload.Comm || 0;
    this.Type = this.mapIncomeType(payload.Type || '');
    this.Percent = payload.Percent || 0;
    this.Paid = payload.Paid || 0;
    this.GST = payload.GST || 0;
    this.Total = payload.Total || 0;
    this.matchedPayIn = payload.matchedPayIn || -1;
  }

  private mapIncomeType( input: string ): string {
    const myMap = new Map();
    myMap.set('tc', 'Trail');
    myMap.set('ufc', 'Upfront');

    if ( myMap.has(input.toLowerCase()) ) {
      return myMap.get(input.toLowerCase());
    }else{
      return input;
    }
  }

  private ensureLenderHasAgencyNameAppended(): void {
    if ( this.Lender.indexOf(this.AgencyName) === -1 ){
      this.Lender += '_' + this.AgencyName;
    }
  }

  public convertToPayIn(): PayInModel {
    const pi = new PayInModel({});
    pi.Lender = this.Lender;
    pi.LoanNumber = this.LoanAccount;
    pi.Amount = this.LoanAmount;
    pi.Settlement = this.Settled;
    pi.IncomeAmount = this.Comm;
    pi.IncomeType = this.Type;
    pi.Balance = this.Balance;
    pi.OffsetBalance = -1;
    pi.Ts = this.Period;

    return pi;
  }

  public isMatch(pi: PayInModel): boolean {
    return  this.LoanAccount === pi.LoanNumber &&  this.LoanAccount !== '' &&
      this.Lender === pi.Lender && this.Lender !== '' &&
      this.Comm === pi.IncomeAmount &&
      this.Balance === pi.Balance &&
      this.Type === pi.IncomeType;
  }
}
