import {Component, Input, OnInit, ViewChild} 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';
import {PopupIncomeFilterComponent} from '../popup-income-filter/popup-income-filter.component';
import {PageChangeEvent, SortSettings} from '@progress/kendo-angular-grid';
import {SortDescriptor} from '@progress/kendo-data-query';

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() allowAddNew = true;
  @Input() allowEdit = true;
  @Input() filter: PayInListFilterModel = new PayInListFilterModel({});
  @ViewChild('filterDialog', {static: true}) filterDialog: PopupIncomeFilterComponent;

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

  public showBalance = true;
  public showOffsetBalance = true;

  public pageable = true;
  public sortable: SortSettings = {
    mode: 'single'
  };
  public filterable = false;

  public loading = false;

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

  ngOnInit(): void {
    this.loadFilteredData();
  }

  public loadFilteredData(): void{
    this.loading = true;
    this.pis.getPayInList(this.filter).subscribe(
      ( resp: PayInListResult) => {
        this.gridData.total = resp.total;
        this.gridData.data = [];
        resp.data.forEach(v => {
          this.gridData.data.push(new PayInModel(v));
          this.loading = false;
        });
      }, err => {
        this.loading = false;
      }, () => {
        this.loading = false;
      }
    );
  }

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

    const balance = -1;
    const offsetBalance = -1;
    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]);
  }

  public setBalance(): void{
    if ( this.showBalance ){
      this.incomeFormGroup.get('Balance').setValue(0);
    }else{
      this.incomeFormGroup.get('Balance').setValue(-1);
    }
  }

  public setOffsetBalance(): void{
    if ( this.showOffsetBalance ){
      this.incomeFormGroup.get('OffsetBalance').setValue(0);
    }else{
      this.incomeFormGroup.get('OffsetBalance').setValue(-1);
    }
  }

  public showFilter(): void{
    this.filterDialog.show();
  }

  public doFilter(filter: PayInListFilterModel): void {
    this.filter.BalanceTo = filter.BalanceTo;
    this.filter.BalanceFrom = filter.BalanceFrom;
    this.filter.AmountFrom = filter.AmountFrom;
    this.filter.AmountTo = filter.AmountTo;

    this.filter.Take = filter.Take;
    this.filter.TrailFrom = filter.TrailFrom;
    this.filter.TrailTo = filter.TrailTo;
    this.filter.IdFrom = filter.IdFrom;
    this.filter.IdTo = filter.IdTo;
    this.filter.TsFrom  = filter.TsFrom;
    this.filter.TsTo = filter.TsTo;
    this.loadFilteredData();
  }

  public pageChange(event: PageChangeEvent): void {
    this.filter.Skip = event.skip;
    this.loadFilteredData();
  }

  public sortChange(sort: SortDescriptor[]): void {
    this.filter.Sort = sort;
    this.loadFilteredData();
  }
}
