import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { GroupsService } from '../groups.service';
import { Group } 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';

@Component({
  selector: 'app-group-details',
  templateUrl: './group-details.component.html',
  styleUrls: ['./group-details.component.css']
})
export class GroupDetailsComponent implements OnInit, OnDestroy {
  id: number;
  currentUser;
  dataToDisplay = '';
  public group: Group;
  data;
  display = false;
  whatToDelete;
  groupDetailsSubscription: Subscription;
  resourceDeleteSubscription: Subscription;
  flashcardsSusbscritpion: Subscription;
  materialsSubscription: Subscription;
  testsSubscription: Subscription;
  localeText = localeText;
  public gridApi;
  public gridOptions: GridOptions;

  displayAvailability = false;

  dateFrom: Date = new Date();
  howLong = 10;
  testId = 1;

  minDate: Date = new Date();

  columnDefs = [
    { headerName: 'Nazwa', field: 'title', headerTooltip: 'Nazwa' },
    { headerName: 'Ocena', field: 'grade', headerTooltip: 'Ocena' },
    { headerName: 'Max.', field: 'maxScore', headerTooltip: 'Max.', hide: false  },
    { headerName: 'Start', field: 'startDate', headerTooltip: 'Start' },
    {
      headerName: '',
      suppressMenu: true,
      suppressSorting: true,
      cellRenderer: this.customCellRendererFunc
    }
  ];
  timetest: number;

  timeout: any;

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


  customCellRendererFunc(params) {
    const currentUsername = JSON.parse(localStorage.getItem('currentUser')).username;
    const groupOwnerUsername = localStorage.getItem('groupOwnerUsername');
    let btns = '';
    if (groupOwnerUsername === currentUsername) {
      btns += `<button type="button" data-action-type="edit" class="btn btn-study-cave mr-2" title="Edytuj">
      <i class="fas fa-edit" data-action-type="edit"></i>
      </button>`;
      btns += `<button type="button" data-action-type="remove" class="btn btn-study-cave" title="Usuń">
      <i class="fas fa-trash-alt" data-action-type="remove"></i>
      </button>`;
    }
    return btns;
  }

  showAvailabilityDialog(data) {
    console.log(data);
    this.testId = data.id;
    if (data['dateFrom']) {
      this.dateFrom = new Date(data['dateFrom']);
      this.howLong = Math.round((data['dateTo'] - data['dateFrom']) / 1000 / 60);
    }
    this.displayAvailability = true;
  }

  editTestAvailability() {
    let dateFrom = null;
    let dateTo = null;
    if (this.dateFrom) {
      dateFrom = this.dateFrom.getTime() - this.dateFrom.getSeconds() * 1000 - this.dateFrom.getMilliseconds();
      dateTo = dateFrom + this.howLong * 60 * 1000;
    }
    this.groupService.putTestsToGroup(this.id, [this.testId.toString()], dateFrom, dateTo).subscribe(
      success => {
        this.snackBar.open('Prawidłowo edytowano przedział czasowy.', null,
          { duration: 3000, verticalPosition: 'top', panelClass: ['snackbar-success'] });
        this.displayAvailability = false;
        this.isDisplayed('testów');
      },
      error => {
        this.snackBar.open('Wystąpił błąd serwera. Spróbuj ponownie później.', null,
          { duration: 3000, verticalPosition: 'top', panelClass: ['snackbar-error'] });
      }
    );
  }

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

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

  public onRowClicked(e) {
    if (e.event.target !== undefined) {
      const data = e.data;
      const now1 = new Date();
      const now = now1.getTime();
      const actionType = e.event.target.getAttribute('data-action-type');
      const temp = new Date(data['dateFrom']);
      const timetest = temp.getTime();
      const tempstop = new Date(data['dateTo']);
      const timeteststop = tempstop.getTime();
      const currentUsername = JSON.parse(localStorage.getItem('currentUser')).username;
      const groupOwnerUsername = localStorage.getItem('groupOwnerUsername');
      if ((groupOwnerUsername === currentUsername) || (timetest < now && now < timeteststop)) {
      switch (actionType) {
        case 'remove':
          return this.onActionRemoveClick(e);
        case 'edit':
          return this.showAvailabilityDialog(e.data);
        default:
          this.goTo(e);
      }
    } else {
      switch (actionType) {
        case 'remove':
          return this.onActionRemoveClick(e);
        case 'edit':
          return this.showAvailabilityDialog(e.data);
        default:
        this.noTime();
      }
    }

    }
  }

  noTime() {
    this.snackBar.open('Test jest nieaktywny.', null,
    { duration: 3000, verticalPosition: 'top', panelClass: ['snackbar-error'] });
  }

  goTo(event: RowDoubleClickedEvent) {
    if (this.dataToDisplay === 'fiszek') {
      this.router.navigate(['flashcards/sets', event.data.id]);

    }
    if (this.dataToDisplay === 'materiałów') {
      this.router.navigate(['materials', event.data.id]);

    }
    if (this.dataToDisplay === 'testów') {
      this.router.navigate(['tests', event.data.id]);
    }
  }


  redirectTo(uri) {
    this.router.navigateByUrl('/', { skipLocationChange: true }).then(() =>
      this.router.navigate([uri]));
  }

  public onActionRemoveClick(e) {
    this.whatToDelete = e.data.id;
    this.display = true;
  }

  deleteResource() {
    if (this.dataToDisplay === 'fiszek') {
        this.resourceDeleteSubscription = this.groupService.deleteResource(this.id, 'sets', this.whatToDelete).subscribe(
          data => {
            this.isDisplayed('fiszek');
            this.display = false;
            this.gridApi.refreshCells();
          }
        );

    }
    if (this.dataToDisplay === 'materiałów') {
        this.resourceDeleteSubscription = this.groupService.deleteResource(this.id, 'materials', this.whatToDelete).subscribe(
          data => {
            this.isDisplayed('materiałów');
            this.display = false;
            this.gridApi.refreshCells();
          }
        );

    }
    if (this.dataToDisplay === 'testów') {
        this.resourceDeleteSubscription = this.groupService.deleteResource(this.id, 'tests', this.whatToDelete).subscribe(
          data => {
            this.isDisplayed('testów');
            this.display = false;
            this.gridApi.refreshCells();
          }
        );

    }

  }

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

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

  onGridSizeChanged(params) {
    const currentUsername = JSON.parse(localStorage.getItem('currentUser')).username;
    const groupOwnerUsername = localStorage.getItem('groupOwnerUsername');
    if (params.clientWidth < 800) {
      if (groupOwnerUsername === currentUsername) {
        this.columnDefs = [
          { headerName: 'Nazwa', field: 'title', headerTooltip: 'Nazwa' },
          { headerName: 'Ocena', field: 'grade', headerTooltip: 'Ocena' },
          { headerName: 'Max.', field: 'maxScore', headerTooltip: 'Max.', hide: true },
          { headerName: 'Start', field: 'startDate', headerTooltip: 'Start'},
          {
            headerName: '',
            suppressMenu: true,
            suppressSorting: true,
            cellRenderer: this.customCellRendererFunc
          }
        ];
      } else {
        this.columnDefs = [
          { headerName: 'Nazwa', field: 'title', headerTooltip: 'Nazwa' },
          { headerName: 'Ocena', field: 'grade', headerTooltip: 'Ocena' },
          { headerName: 'Max.', field: 'maxScore', headerTooltip: 'Max.', hide: true },
          { headerName: 'Start', field: 'startDate', headerTooltip: 'Start'},
        ];
      }
    } else {
      if (groupOwnerUsername === currentUsername) {
        this.columnDefs = [
          { headerName: 'Nazwa', field: 'title', headerTooltip: 'Nazwa' },
          { headerName: 'Ocena', field: 'grade', headerTooltip: 'Ocena' },
          { headerName: 'Max.', field: 'maxScore', headerTooltip: 'Max.' },
          { headerName: 'Start', field: 'startDate', headerTooltip: 'Start'},
          {
            headerName: '',
            suppressMenu: true,
            suppressSorting: true,
            cellRenderer: this.customCellRendererFunc
          }
        ];
      } else {
        this.columnDefs = [
          { headerName: 'Nazwa', field: 'title', headerTooltip: 'Nazwa' },
          { headerName: 'Ocena', field: 'grade', headerTooltip: 'Ocena' },
          { headerName: 'Max.', field: 'maxScore', headerTooltip: 'Max.' },
          { headerName: 'Start', field: 'startDate', headerTooltip: 'Start'}
        ];
      }
    }

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

  ngOnDestroy() {
    if (this.groupDetailsSubscription) {
      this.groupDetailsSubscription.unsubscribe();
    }

    if (this.flashcardsSusbscritpion) {
      this.flashcardsSusbscritpion.unsubscribe();
    }
    if (this.materialsSubscription) {
      this.materialsSubscription.unsubscribe();
    }
    if (this.testsSubscription) {
      this.testsSubscription.unsubscribe();
    }
    if (this.resourceDeleteSubscription) {
      this.resourceDeleteSubscription.unsubscribe();
    }
    localStorage.removeItem('groupOwnerUsername');
  }

  goToEditing() {
    this.router.navigate(['groups/manage', this.id]);
  }
  isDisplayed(resource) {
    if (resource === 'fiszek') {
      this.localeText.noRowsToShow = 'Brak fiszek do wyświetlenia';
      setTimeout(() => {
        this.flashcardsSusbscritpion = this.groupService.getResource(this.id, 'flashcardsets').subscribe(data => this.data = data);
        this.dataToDisplay = resource;
      }, 200);

    }
    if (resource === 'materiałów') {
      this.localeText.noRowsToShow = 'Brak materiałów do wyświetlenia';
      setTimeout(() => {
        this.materialsSubscription = this.groupService.getResource(this.id, 'materials').subscribe(data => this.data = data);
        this.dataToDisplay = resource;
      }, 200);

    }
    if (resource === 'testów') {
      this.localeText.noRowsToShow = 'Brak testów do wyświetlenia';
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.timeout = setTimeout(() => {
        this.testsSubscription = this.groupService.getResource(this.id, 'tests').subscribe(data => {
          this.data = data;
          data.forEach(x => {
            const temp = new Date(x['dateFrom']);
            const tempstop = new Date(x['dateTo']);
            x['startDate'] = '';
            const hoursTemp = temp.getHours();
            let hours = hoursTemp.toString();
            if (hoursTemp < 10) {
              hours = `0${hoursTemp}`;
            }
            const minutesTemp = temp.getMinutes();
            let minutes = minutesTemp.toString();
            if (minutesTemp < 10) {
              minutes = `0${minutesTemp}`;
            }
            // const months = ['STY', 'LUT', 'MAR', 'KWI', 'MAJ', 'CZE', 'LIP', 'SIE', 'WRZ', 'PAŹ', 'LIS', 'GRU'];
            const year = temp.getFullYear().toString().substring(2);
            const monthTemp = (temp.getMonth() + 1);
            let month = monthTemp.toString();
            if (monthTemp < 10) {
              month = `0${monthTemp}`;
            }
            const dateTemp = temp.getDate();
            let date = dateTemp.toString();
            if (dateTemp < 10) {
              date = `0${dateTemp}`;
            }
            const time = date + '.' + month + '.' + year + ' ' + hours + ':' + minutes;
            x['startDate'] += time;
          });
        });
        this.dataToDisplay = resource;
      }, 200);

    }
  }

  goToAddingResource() {
    this.router.navigate(['groups/add-resources', this.id]);
  }

  goToRankings() {
    this.router.navigate(['groups/ranking', this.id]);
  }

  goToTestsResults() {
    this.router.navigate(['groups/tests-results', this.id]);
  }

  goToHistory() {
    this.router.navigate(['groups/history', this.id]);
  }

  goToGroupsList() {
    this.router.navigate(['/my-groups/']);
  }
}
