import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GroupsService } from '../groups.service';
import { Group, TestsInGroup, TestsInGroupResults } from '../group';
import { Subscription } from 'rxjs/Subscription';
import localeText from './../../../assets/localeText';
import { GridOptions, RowDoubleClickedEvent } from 'ag-grid-community/main';
import { MatSnackBar } from '@angular/material';
import { ngxCsv } from 'ngx-csv/ngx-csv';


@Component({
  selector: 'app-tests-in-group-results',
  templateUrl: './tests-in-group-results.component.html',
  styleUrls: ['./tests-in-group-results.component.css']
})
export class TestsInGroupResultsComponent implements OnInit, OnDestroy {

  id: number;
  currentUser;
  subs: Subscription[] = [];
  public group: Group;
  public selectedTest: TestsInGroup;

  public localeText = localeText;

  // chooseTests
  public data: TestsInGroup[] = [];
  public gridApi;
  public gridOptions: GridOptions;
  public columnDefs = [
    { headerName: 'ID', field: 'id', headerTooltip: 'ID' },
    { headerName: 'Nazwa', field: 'title', headerTooltip: 'Nazwa' },
    { headerName: 'Max.', field: 'maxScore', headerTooltip: 'Liczba punktów do zdobycia', hide: false }
  ];

  // showTestResult
  public testdata: TestsInGroupResults[] = [];
  public testgridApi;
  public testgridOptions: GridOptions;
  public testcolumnDefs = [
    { headerName: 'Imię', field: 'name', headerTooltip: 'Imię' },
    { headerName: 'Nazwisko', field: 'surname', headerTooltip: 'Nazwisko' },
    { headerName: 'Wynik', field: 'userScore', headerTooltip: 'Wynik', hide: false },
    { headerName: 'Wynik (%)', field: 'percent', headerTooltip: 'Wynik (%)', hide: false }
  ];

  constructor(private route: ActivatedRoute,
              private groupService: GroupsService,
              public snackBar: MatSnackBar) { }

  ngOnInit() {
    this.id = this.route.snapshot.params.id;
    this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.subs.push(
      this.groupService.getGroupDetails(this.id)
      .subscribe(
        data => {
          this.group = data;
          this.getTests();
          localStorage.setItem('groupOwnerUsername', this.group.owner);
        }
      )
    );

    this.gridOptions = {
      rowHeight: 50,
      headerHeight: 25,
      getRowStyle: function (params) {
        return {
          cursor: 'pointer'
        };
      },
    };

    this.testgridOptions = {
      rowHeight: 50,
      headerHeight: 25,
      getRowStyle: function (params) {
        return {
          cursor: 'pointer'
        };
      },
    };
  }

  getTests() {
    this.subs.push(this.groupService.getTestsInGroups(this.id).subscribe(
      success => {
        this.data = success;
      },
      error => {
        console.log(error);
        this.snackBar.open('Nie udało się załadować listy testów!', null,
          { duration: 3000, verticalPosition: 'top', panelClass: ['snackbar-error'] });
      }
    ));
  }

  goTo(event: RowDoubleClickedEvent) {
    this.selectedTest = event.data;
    this.getResults(event.data.id);
  }

  downloadCSVResults() {
    const options = {
      fieldSeparator: ';',
      quoteStrings: '',
      decimalseparator: ',',
      showLabels: true,
      headers: ['Imię', 'Nazwisko', 'Wynik', 'Wynik (%)']
    };
    // tslint:disable-next-line:no-unused-expression
    new ngxCsv(this.testdata, this.group.name + '_' + this.selectedTest.title + '_wyniki', options);
  }

  getResults(id: number) {
    this.subs.push(this.groupService.getResultsInTests(this.id, id).subscribe(
      success => {
        this.testdata = success;
      },
      error => {
        console.log(error);
        this.snackBar.open('Nie udało się załadować wyników za test!', null,
          { duration: 3000, verticalPosition: 'top', panelClass: ['snackbar-error'] });
      }
    ));
  }

  ngOnDestroy() {
    if (this.subs) {
      this.subs.forEach(x => x.unsubscribe());
    }

    localStorage.removeItem('groupOwnerUsername');
  }

  // chooseTests
  public onRowClicked(e) {
    if (e.event.target !== undefined) {
      this.goTo(e);
    }
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridApi.sizeColumnsToFit();
  }

  onGridColumnsChanged(params) {
    params.api.sizeColumnsToFit();
  }

  onGridSizeChanged(params) {
    this.columnDefs = [
      { headerName: 'ID', field: 'id', headerTooltip: 'ID' },
      { headerName: 'Nazwa', field: 'title', headerTooltip: 'Nazwa' },
      { headerName: 'Max.', field: 'maxScore', headerTooltip: 'Liczba punktów do zdobycia', hide: false }
    ];

    params.api.sizeColumnsToFit();
  }

  onGidColumnsChanged(params) {
    params.api.sizeColumnsToFit();
  }

  // showTestResult
  public testonRowClicked(e) {}

  testonGridReady(params) {
    this.testgridApi = params.api;
    this.testgridApi.sizeColumnsToFit();
  }

  testonGridColumnsChanged(params) {
    params.api.sizeColumnsToFit();
  }

  testonGridSizeChanged(params) {
    this.testcolumnDefs = [
      { headerName: 'Imię', field: 'name', headerTooltip: 'Imię' },
      { headerName: 'Nazwisko', field: 'surname', headerTooltip: 'Nazwisko' },
      { headerName: 'Wynik', field: 'userScore', headerTooltip: 'Wynik', hide: false },
      { headerName: 'Wynik (%)', field: 'percent', headerTooltip: 'Wynik (%)', hide: false }
    ];

    params.api.sizeColumnsToFit();
  }

  testonGidColumnsChanged(params) {
    params.api.sizeColumnsToFit();
  }

}
