import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { LoggingService, TokenService } from '@app/_services';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { exportCsv } from '@app/_helpers';
import { TokenRegistry } from '../../_eth';
import { Token } from '../../_models';

@Component({
  selector: 'app-tokens',
  templateUrl: './tokens.component.html',
  styleUrls: ['./tokens.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TokensComponent implements OnInit {
  dataSource: MatTableDataSource<any>;
  columnsToDisplay: Array<string> = ['name', 'symbol', 'address', 'supply'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  tokens: Array<Promise<string>>;

  constructor(
    private tokenService: TokenService,
    private loggingService: LoggingService,
    private router: Router
  ) {}

  async ngOnInit(): Promise<void> {
    this.tokenService.LoadEvent.subscribe(async () => {
      this.tokens = await this.tokenService.getTokens();
    });
    this.tokens = await this.tokenService.getTokens();
    this.loggingService.sendInfoLevelMessage(this.tokens);
    this.dataSource = new MatTableDataSource(this.tokens);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

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

  async viewToken(token): Promise<void> {
    await this.router.navigateByUrl(`/tokens/${token.symbol}`);
  }

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