import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { PageEvent } from '@angular/material/paginator';
import { Sort } from '@angular/material/sort';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { debounceTime, Observable, switchMap } from 'rxjs';
import { I18nService } from 'src/app/services/i18n.service';
import { TurnoverManagementService } from 'src/app/services/turnover.management.service';
import { UserManagementService } from 'src/app/services/user.management.service';
import { UiTurnovers } from 'src/app/ui/turnovers/turnovers.ui';

@Component({
  selector: 'ui-management',
  templateUrl: './management.page.html',
  styleUrls: ['./management.page.scss']
})
export class PageManagement implements OnInit {

  @Input() entries: any;
  pageSizeOptions: number[] = [1, 2, 3, 4, 5, 10, 15, 30, 50, 100];
  sort: string = "username";
  descending: boolean = false;
  filterOpen: boolean = true;

  columns: string[] = ['username', 'price', 'timeInvestment', 'giftcardPrice', 'menu'];
  expanded: boolean = false;

  users: Observable<any>;
  usersFormControl = new FormControl();

  @ViewChild('uiTurnovers') uiTurnovers: UiTurnovers;

  turnovers: any;

  constructor(
    private turnoverManagementService: TurnoverManagementService,
    private userManagementService: UserManagementService,
    private i18n: I18nService,
    private router: Router,
    private route: ActivatedRoute
  ) { }

  ngOnInit(): void {
    this.entries = {};
    this.turnovers = {};
    this.users = this.usersFormControl
      .valueChanges
      .pipe(
        debounceTime(300),
        switchMap(value => this.userManagementService.pick(value))
      );

    this.route.queryParams.subscribe({
      next: (params) => {
        this.entries = { filter: {} };
        this.expanded = false;
        if (params['l']) {
          this.entries.limit = +params['l'];
          if (this.entries.limit < 1) {
            this.entries.limit = 1;
          }
        }
        if (params['o']) {
          this.entries.offset = +params['o'];
          if (this.entries.offset < 0) {
            this.entries.offset = 0;
          }
        }

        if (params['s']) {
          this.sort = params['s'];
        }

        if (params['a']) {
          this.descending = false;
        } else {
          this.descending = true;
        }

        for (const param in params) {
          if (param != 'l' && param != 'o' && param != 's' && param != 'a') {
            this.entries.filter[param] = params[param];
          }
        }

        this.refresh();
      }
    });
  }

  refresh() {
    const filter = JSON.parse(JSON.stringify(this.entries.filter || {}));
    this.turnoverManagementService.overview(this.entries.limit || 15, this.entries.offset || 0, this.sort, this.descending, filter).subscribe({
      next: (data: any) => {
        this.entries = data;
        this.entries.filter = filter;
        if (filter.username) {
          this.applyUser(filter.username);
        }
      }, error: (error) => {
        this.entries = { error: error };
      }
    })
  }

  update() {
    const filter = JSON.parse(JSON.stringify(this.entries.filter || {}));

    const params: Params = { l: null, o: null, s: null, a: null };

    if ((this.entries.limit || 15) != 15) {
      params['l'] = this.entries.limit;
    }

    if ((this.entries.offset || 0) != 0) {
      params['o'] = this.entries.offset;
    }

    if (this.sort != 'username') {
      params['s'] = this.sort;
    }

    if (!this.descending) {
      params['a'] = true;
    }

    if (filter) {
      for (const param in filter) {
        params[param] = filter[param] || null;
      }
    }

    this.router.navigate(
      [],
      {
        relativeTo: this.route,
        queryParams: params,
        queryParamsHandling: 'replace'
      });
  }

  applyPage(event: PageEvent) {
    this.entries.limit = event.pageSize;
    this.entries.offset = event.pageSize * event.pageIndex;
    this.update();
  }

  applySort(event: Sort) {
    this.sort = event.direction ? event.active : 'username';
    this.descending = event.direction !== 'asc';
    this.update();
  }

  setInputFilter(key: string, target: EventTarget) {
    this.setFilter(key, (target as HTMLInputElement).value);
  }

  setFilter(key: string, value) {
    if (value != this.entries.filter[key]) {
      this.entries.filter[key] = value;
      this.entries.offset = 0;
      this.update();
    }
  }

  selectUser(username: string) {
    this.router.navigate(
      [],
      {
        relativeTo: this.route,
        queryParams: { username: this.entries.filter && this.entries.filter.username == username ? null : username },
        queryParamsHandling: 'merge'
      });
  }

  applyUser(username: string) {
    this.usersFormControl.setValue(username);
    if (this.entries.total) {
      this.expanded = true;
      const filter = JSON.parse(JSON.stringify(this.entries.filter || {}));
      this.turnoverManagementService.fetch(this.turnovers.limit || 100, this.turnovers.offset || 0, 'dueDate', true, filter).subscribe({
        next: (data: any) => {
          this.turnovers = data;
          this.turnovers.filter = filter;
        }, error: (error) => {
          this.turnovers = { error: error };
        }
      })
    }
  }

  applyTurnoverPage(event: PageEvent) {
    this.turnovers.limit = event.pageSize;
    this.turnovers.offset = event.pageSize * event.pageIndex;
    this.applyUser(this.usersFormControl.value);
  }


  export() {
    if (this.entries.total) {
      let rows = [[this.i18n.get('user.username'), this.i18n.get('turnover.price'), this.i18n.get('turnover.timeInvestment'), this.i18n.get('turnover.giftcard.priceUsage')]];

      this.entries.results.forEach(result => {
        rows[rows.length] = [result[0], result[1], result[2], result[3]]
      });

      if (this.uiTurnovers) {
        rows.push(...this.uiTurnovers.getCsvRows());
      }

      if (rows.length) {
        let csvContent = "data:text/csv;charset=utf-8,"
          + rows.map(e => e.join(";")).join("\n");

        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "export.csv");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  }

}
