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 { SecurityService } from '../../logic/services/security.service';

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

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


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

  gridColumnDefs = [
    {
      headerName: 'Код',
      field: 'id'
    },
    {
      headerName: 'Наименование',
      field: 'caption',
    },
    {
      headerName: 'Адрес',
      field: 'address'
    }];

  constructor(private supplierService: SupplierService,
              private router: Router,
              public securityService: SecurityService) {
  }

  ngOnInit() {
    this.loadData();
  }

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

  refreshFormData() {
    this.supplierService.clearSuppliers();
    this.loadData();
  }

  loadData() {
    this.isLoading = true;
    this.rowData = [];
    this.supplierService.getSuppliers$()
      .subscribe(suppliers => {
        this.setData(suppliers);
      });

  }

  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.6 : gridWidth * 0.3);
    });
  }

  createNewSupplier() {
    this.router.navigate(['/edit-supplier/0']).then();
  }

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