import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  OnInit,
  ViewChild,
} from '@angular/core';
import { BlockSyncService, TransactionService, UserService } from '@app/_services';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { exportCsv } from '@app/_helpers';
import { first } from 'rxjs/operators';
import { Transaction } from '@app/_models';

@Component({
  selector: 'app-transactions',
  templateUrl: './transactions.component.html',
  styleUrls: ['./transactions.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TransactionsComponent implements OnInit, AfterViewInit {
  transactionDataSource: MatTableDataSource<any>;
  transactionDisplayedColumns: Array<string> = ['sender', 'recipient', 'value', 'created', 'type'];
  defaultPageSize: number = 10;
  pageSizeOptions: Array<number> = [10, 20, 50, 100];
  transactions: Array<Transaction>;
  transaction: Transaction;
  transactionsType: string = 'all';
  transactionsTypes: Array<string>;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(
    private blockSyncService: BlockSyncService,
    private transactionService: TransactionService,
    private userService: UserService
  ) {
    this.blockSyncService.blockSync();
  }

  ngOnInit(): void {
    this.transactionService.transactionsSubject.subscribe((transactions) => {
      this.transactionDataSource = new MatTableDataSource<any>(transactions);
      this.transactionDataSource.paginator = this.paginator;
      this.transactionDataSource.sort = this.sort;
      this.transactions = transactions;
    });
    this.userService
      .getTransactionTypes()
      .pipe(first())
      .subscribe((res) => (this.transactionsTypes = res));
  }

  viewTransaction(transaction): void {
    this.transaction = transaction;
  }

  doFilter(value: string, dataSource): void {
    dataSource.filter = value.trim().toLocaleLowerCase();
  }

  filterTransactions(): void {
    if (this.transactionsType === 'all') {
      this.transactionService.transactionsSubject.subscribe((transactions) => {
        this.transactionDataSource.data = transactions;
        this.transactions = transactions;
      });
    } else {
      this.transactionDataSource.data = this.transactions.filter(
        (transaction) => transaction.type === this.transactionsType
      );
    }
  }

  ngAfterViewInit(): void {
    this.transactionDataSource.paginator = this.paginator;
    this.transactionDataSource.sort = this.sort;
  }

  downloadCsv(): void {
    exportCsv(this.transactions, 'transactions');
  }
}
