import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ListAllLoansComponent} from '../list-all-loans/list-all-loans.component';
import {LoanModel} from '../models/loan.model';
import {RewardModel} from '../models/reward.model';
import {RewardExModel} from '../models/reward-ex.model';

@Component({
  selector: 'app-reward-select',
  templateUrl: './reward-select.component.html',
  styleUrls: ['./reward-select.component.scss']
})
export class RewardSelectComponent implements OnInit {
  // @ViewChild('list', {static: false} ) list: list-all;
  @Input() Max = 1; // we do not support multiple loan selection at the moment
  @Input() readOnly = false;
  @Input() showNonPaidOnly = false;
  @Output() valueChange: EventEmitter<RewardExModel[]> = new EventEmitter<RewardExModel[]>();
  @Input() public selectedRewards: RewardExModel[] = [];


  // popup
  public showPopup = false;
  public Offset = { left: 10, top: 48 };

  constructor() { }

  ngOnInit(): void {
  }

  public onToggle(): void {
    this.showPopup = !this.showPopup;
  }

  public onConfirmSelection(sel: RewardExModel[]): void {
    if (this.isDiff(this.selectedRewards, sel)) {
      this.valueChange.emit (sel);
      this.selectedRewards = sel;
      console.log('reward-select', this.selectedRewards);
    }
    this.showPopup = !this.showPopup;
  }

  private isDiff(a: RewardExModel[], b: RewardExModel[]): boolean {
    if ( !a || !b ) {    return a !== b;   }
    if ( a.length !== b.length) { return true; }
    for ( let i = 0; i < a.length; i++ ){
      if ( ! a[i].Equal(b[i]) ){
        return true;
      }
    }
    return false;
  }
}
