import {Component, Input, OnInit, Output, EventEmitter} from '@angular/core';
import {FormControl, FormGroup, NgForm, Validators} from '@angular/forms';
import {LoanModel} from '../../models/loan.model';
import {LoanSingleService} from '../../service/loan.single.service';
import {AuthService} from '../../service/auth.service';
import {PayInModel} from '../../models/pay-in.model';
import {Router} from '@angular/router';


const createFormGroup = dataItem => new FormGroup({
  Id: new FormControl({value: dataItem.Id, disabled: true}, Validators.required),
  Trail  : new FormControl(dataItem.Trail, Validators.required),
  Ts: new FormControl(dataItem.Ts, Validators.required),
  Balance: new FormControl(dataItem.Balance, Validators.required),
  OffsetBalance: new FormControl(dataItem.OffsetBalance, Validators.required),
});

@Component({
  selector: 'app-loan-trail-income',
  templateUrl: './trail-income.component.html',
  styleUrls: ['./trail-income.component.scss']
})
export class TrailIncomeComponent implements OnInit {
  @Input() public Loan: LoanModel;

  @Output() public NotifyNext = new EventEmitter<boolean>();
  @Output() public NotifyPrev = new EventEmitter<boolean>();
  @Output() public errorOccurred = new EventEmitter<string>();

  public formGroup: FormGroup;
  private editedRowIndex: number;

  public trailIncome: FormGroup;
  public showBalance = true;
  public showOffsetBalance = true;

  constructor(private ls: LoanSingleService,
              private auth: AuthService,
              private router: Router) { }
  ngOnInit(): void {
    // this.Loan.PayIn
  }

  public addHandler({ sender }): void  {
    this.closeEditor(sender);

    let balance = -1;
    let offsetBalance = -1;
    if ( this.Loan.PayIn.length > 0) {
      const idx = this.Loan.PayIn.length - 1;
      balance = this.Loan.PayIn[idx].Balance;
      offsetBalance = this.Loan.PayIn[idx].OffsetBalance;
    }

    this.showBalance = balance >= 0 ;
    this.showOffsetBalance = offsetBalance >= 0 ;

    this.formGroup = createFormGroup({
      Id: 0,
      Trail: 168,
      Ts: new Date(),
      Balance: balance,
      OffsetBalance: offsetBalance,
    });

    sender.addRow(this.formGroup);
  }

  public editHandler({ sender, rowIndex, dataItem }): void {
    this.closeEditor(sender);

    this.showBalance = dataItem.Balance >= 0 ;
    this.showOffsetBalance = dataItem.OffsetBalance >= 0 ;
    this.formGroup = createFormGroup(dataItem);
    this.editedRowIndex = rowIndex;
    sender.editRow(rowIndex, this.formGroup);

  }

  public cancelHandler({ sender, rowIndex }): void {
    console.log(sender);
    this.closeEditor(sender, rowIndex);
  }

  public saveHandler({ sender, rowIndex, formGroup, isNew }): void {
    const v = formGroup.getRawValue();

    if ( this.Loan.Lender === '')  {
      this.errorOccurred.emit('Lender should not be empty');
      return;
    }

    if ( this.Loan.LenderLoanNumber === '')  {
      this.errorOccurred.emit('Lender Identification should not be empty');
      return;
    }

    if ( !this.showBalance) { v.Balance = -1; }
    if ( !this.showOffsetBalance) { v.OffsetBalance = -1; }

    const pi = new PayInModel({});
    pi.Id = v.Id;
    pi.Amount = this.Loan.Amount;
    pi.Balance = v.Balance;
    pi.Lender = this.Loan.Lender;
    pi.LoanId = this.Loan.Id;
    pi.LoanNumber = this.Loan.LenderLoanNumber;
    pi.OffsetBalance = v.OffsetBalance;
    pi.Settlement = this.Loan.Settlement;
    pi.Trail = v.Trail;
    pi.Ts = new Date(v.Ts);
    pi.UploadId = v.UploadId;


    console.log('saving PayIn', pi);
    this.ls.savePayIn(pi, isNew).subscribe(
      (resp: PayInModel) => {
        this.Loan.cuPayIn(resp);
      },
      err => {
        this.errorOccurred.emit('Error saving Income');
      }
    );

    sender.closeRow(rowIndex);
  }

  public removeHandler({ dataItem }): void {
    console.log(dataItem);

    const na = this.Loan.PayIn.filter(v => {
      return v.Id !== dataItem.Id;
    });

    this.Loan.PayIn = na;
    this.ls.removePayIn(dataItem.Id);
  }

  private closeEditor(grid, rowIndex = this.editedRowIndex): void{
    grid.closeRow(rowIndex);
    this.editedRowIndex = undefined;
    this.formGroup = undefined;
  }

  public next(trailIncome: NgForm): void{
    this.NotifyNext.emit(true);
    this.router.navigate(['./list-all-loans']);
  }

  public prev(): void {
    this.NotifyPrev.emit(true);
  }

  public visitUploads(pi: PayInModel): void {
    this.router.navigate(['./uploads/' + pi.UploadId]);
  }

}
