import {Component, Input, OnInit} from '@angular/core';
import {PayInModel} from '../models/pay-in.model';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {PayInListFilterModel} from '../models/pay-in-list.filter.model';
import {PayInService} from '../service/pay-in.service';
import {PayInListResult} from '../models/pay-in-list-result.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-pay-in',
  templateUrl: './pay-in.component.html',
  styleUrls: ['./pay-in.component.scss']
})
export class PayInComponent implements OnInit {
  @Input() loanFilter: string[] = [];
  @Input() uploadsFilter: string[] = [];
  @Input() allowAddNew = true;
  @Input() allowEdit = true;
  @Input() pageSize = 10;
  @Input() skip = 0;
  @Input() dateStart = new Date('1900-01-01');
  @Input() dateEnd = new Date('2038-12-31');

  public gridData: PayInListResult = { data: [], total: 0};
  public incomeFormGroup: FormGroup;
  private editedRowIndex: number;

  public showBalance = true;
  public showOffsetBalance = true;


  constructor(private pis: PayInService, private router: Router) { }

  ngOnInit(): void {
    this.pis.getPayInList(new PayInListFilterModel()).subscribe(
      ( resp: PayInListResult) => {
        console.log(resp);
        this.gridData = resp;
      }
    );
  }


  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.incomeFormGroup = createFormGroup({
      Id: 0,
      Trail: 168,
      Ts: new Date(),
      Balance: balance,
      OffsetBalance: offsetBalance
    });

    sender.addRow(this.incomeFormGroup);
  }

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

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

  }

  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.showBalance) { v.Balance = -1; }
    if ( !this.showOffsetBalance) { v.OffsetBalance = -1; }

    // const pi = new PayInModel(
    //   v.Id,
    //   this.Loan.Amount,
    //   v.Balance,
    //   this.Loan.Lender,
    //   this.Loan.Id,
    //   this.Loan.LenderLoanNumber,
    //   v.OffsetBalance,
    //   this.Loan.Settlement,
    //   v.Trail,
    //   v.Ts,
    //   0,
    // );

    //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.incomeFormGroup = undefined;
  }

  public showUpload(id: number): void {
    this.router.navigate(['/upload-details', id]);
  }
  public gotoLoan(id: string): void {
    this.router.navigate(['/edit-loan', id]);
  }
}
