import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {JournalService} from '../../logic/services/journal.service';
import {GridApi} from 'ag-grid-community';
import {DateHelper} from '../../helpers/date-helper';
import {StringHelper} from '../../helpers/string-helper';
import {FormHelper} from '../../ui/controls/form-helper';
import {LookupSourceService} from '../../logic/services/lookup-source.service';
import {JournalDetailCellRendererComponent} from './journal-detail-cell-renderer.component';
import {SecurityService} from '../../logic/services/security.service';

@Component({
  selector: 'app-journal',
  templateUrl: './journal.component.html'
})
export class JournalComponent implements OnInit {

  contextFormGroup: FormGroup;

  rowData = [];
  isLoading = false;
  gridApi: GridApi;

  changeTypeLookup = {};

  public defaultColDef = {
    sortable: true,
    filter: true,
    resizable: true
  };

  gridColumnDefs = [
    {
      headerName: 'Вид изменений',
      field: 'changeTypeId',
      cellRenderer: params =>
        this.changeTypeLookup[params.data.changeTypeId] ? this.changeTypeLookup[params.data.changeTypeId] : '',
    },
    {
      headerName: 'Дата',
      field: 'changeTime',
      valueFormatter: params => StringHelper.getRuTimeWithSeconds(params.value)
    },
    {
      headerName: 'Пользователь',
      field: 'changeUsername'
    },
    {
      headerName: 'Описание',
      field: 'changeCaption',
      cellRenderer: 'agGroupCellRenderer'
    }];

  detailCellRenderer = 'myDetailCellRenderer';
  frameworkComponents = {myDetailCellRenderer: JournalDetailCellRendererComponent};

  private static buildFormGroup(fb: FormBuilder, data: any) {
    return fb.group({
      objTypeId: [data.objTypeId, Validators.required],
      changeTypeId: data.changeTypeId,
      dateFrom: [data.dateFrom, FormHelper.validateDateTimePicker()],
      dateToInclusive: [data.dateToInclusive, FormHelper.validateDateTimePicker()]
    });
  }

  constructor(private fb: FormBuilder,
              private journalService: JournalService,
              private lookupService: LookupSourceService,
              public securityService: SecurityService) {}

  ngOnInit() {
    this.contextFormGroup = JournalComponent.buildFormGroup(this.fb, {});
    this.rowData = [];
    this.lookupService.getLookup('journal/change-type')
      .subscribe(response => response.forEach(type => this.changeTypeLookup[type.id] = type.caption));
  }

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

  isInvalid(controlName: string) {
    return FormHelper.isInvalid(this.contextFormGroup, controlName);
  }

  getJournalData() {

    if (!this.contextFormGroup.valid) {
      FormHelper.setFocusToInvalidControl(this.contextFormGroup);
      return;
    }

    this.isLoading = true;
    if ((this.contextFormGroup.get('dateFrom').value && this.contextFormGroup.get('dateFrom').value !== '') ||
        (this.contextFormGroup.get('dateToInclusive').value && this.contextFormGroup.get('dateToInclusive').value !== '')) {

      const dateFrom = (this.contextFormGroup.get('dateFrom').value && this.contextFormGroup.get('dateFrom').value !== '')
                        ? DateHelper.toDate(this.contextFormGroup.get('dateFrom').value) : new Date(1900, 1, 1);
      const dateToInclusive = (this.contextFormGroup.get('dateToInclusive').value && this.contextFormGroup.get('dateToInclusive').value !== '')
                        ? DateHelper.toDate(this.contextFormGroup.get('dateToInclusive').value) : new Date();

      this.journalService.getJournalWithDatePeriod(StringHelper.getISODate(dateFrom),
                                                   StringHelper.getISODate(dateToInclusive),
                                                   this.contextFormGroup.get('objTypeId').value,
                                                   this.contextFormGroup.get('changeTypeId').value)
        .subscribe(response => this.setData(response));

    } else {
      this.journalService.getJournal(this.contextFormGroup.get('objTypeId').value, this.contextFormGroup.get('changeTypeId').value)
        .subscribe(response => this.setData(response));
    }
  }

  setData(data: any[]) {
    this.isLoading = false;
    data.sort((a, b) => DateHelper.toDate(b.changeTime).getTime() - DateHelper.toDate(a.changeTime).getTime());
    this.rowData = data;
  }

  onGridSizeChanged (params) {
    const gridWidth = params.clientWidth;
    const allColumns = params.columnApi.getAllGridColumns();

    allColumns.forEach((col, index) => {
      params.columnApi.setColumnWidth(col, index === 3 ? gridWidth * 0.399 : gridWidth * 0.2);
    });
  }

}
