import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { GridApi } from 'ag-grid-community';
import { SupplierService } from '../../logic/services/supplier.service';
import { Router } from '@angular/router';
import { SocServiceService } from '../../logic/services/soc-service.service';
import { LookupSourceService } from '../../logic/services/lookup-source.service';
import { SecurityService } from '../../logic/services/security.service';

@Component({
  selector: 'app-list-soc-services',
  templateUrl: './list-soc-services.component.html',
  styleUrls: ['./list-soc-service.component.css']
})
export class ListSocServicesComponent implements OnInit {

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

  lookupDeliveryArea = {};

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

  gridColumnDefs = [
    {
      headerName: 'Код',
      field: 'id'
    },
    {
      headerName: 'Сфера обслуживания',
      field: 'deliveryAreaId',
      cellRenderer: params =>
        this.lookupDeliveryArea[params.data.deliveryAreaId] ? this.lookupDeliveryArea[params.data.deliveryAreaId] : '',
    },
    {
      headerName: 'Наименование',
      field: 'caption',
    }];

  constructor(private supplierService: SupplierService,
              private router: Router,
              private socServiceService: SocServiceService,
              private lookupService: LookupSourceService,
              public securityService: SecurityService) {
  }

  ngOnInit() {
    this.loadDeliveryAreaValues();
    this.loadData();
  }

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

  loadDeliveryAreaValues() {

    // subscribe в грид не засунешь, поэтому создадим временный объект
    this.lookupService.getLookup('delivery-area')
      .subscribe(roles =>
        roles.forEach(role => this.lookupDeliveryArea[role.id] = role.caption));
  }

  refreshFormData() {
    this.socServiceService.clearSocServices();
    this.loadDeliveryAreaValues();
    this.loadData();
  }

  loadData() {
    this.isLoading = true;
    this.rowData = [];
    this.socServiceService.getSocServices$()
      .subscribe(socServices => this.setData(socServices));
  }

  setData(data: any[]) {
    this.rowData = data;
    this.isLoading = false;
  }

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

    allColumns.forEach((col, index) => {
      params.columnApi.setColumnWidth(col, index === 0 ? gridWidth * 0.09 : index === 1 ? gridWidth * 0.3 : gridWidth * 0.6);
    });
  }

  createNewSocService() {
    this.router.navigate(['/edit-soc-service/0']).then();
  }

  editSocService($event) {
    this.router.navigate(['/edit-soc-service/' + $event.data.id]).then();
  }
}
