import {Component, Input, OnInit} from '@angular/core';
import {AccountService} from '../../services/account.service';
import {Account} from '../../models/account.entity';
import {Transaction} from '../../models/transaction.entity';
import {INglDatatableSort} from 'ng-lightning/ng-lightning';

@Component({
  providers: [AccountService],
  selector: 'account-transaction-list',
  templateUrl: './account.transaction.list.component.html',
  styleUrls: ['./account.component.css']
})

export class AccountTransactionListComponent implements OnInit {
  public openTransactionListSelection: boolean = true;

  // Initial sort
  sort: INglDatatableSort = {key: 'transactionNumber', order: 'desc'};

  _account: Account;
  public transactions: Transaction[] = [];

  constructor(private _accountService: AccountService) {
  }

  @Input()
  get account() {
    return this._account;
  }

  set account(val) {
    if (val) {
      this._account = val;
      this.getTransactions();
    }
  }

  onSort($event: INglDatatableSort) {
    const {key, order} = $event;
    this.transactions.sort((a: any, b: any) => {
      if (key === 'value') {
        return b[key] - a[key] * (order === 'desc' ? 1 : -1);
      }
      if (key === 'currency') {
        if (a[key] && b[key]) {
          return b[key].iso.localeCompare(a[key].iso) * (order === 'desc' ? 1 : -1);
        } else {
          if (a[key]) {
            return 1;
          } else {
            return -1;
          }
        }
      }
      else return (b[key].localeCompare(a[key])) * (order === 'desc' ? 1 : -1);
    });
  }

  getTransactions() {
    this._accountService.transactionList(this.account.id).subscribe(
      transactions => {
        this.transactions = transactions.sort((a, b) => a.transactionNumber > b.transactionNumber);
      },
      err => {
        console.log(err);
      });
  }

  ngOnInit() {
  }
}
