import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { MatDialog } from '@angular/material';
import { ApiService } from 'app/api.service';
import { InventoryWarehouseAddComponent } from 'app/inventory-warehouse-add/inventory-warehouse-add.component';

@Component({
  selector: 'app-inventory-warehouse',
  templateUrl: './inventory-warehouse.component.html',
  styleUrls: ['./inventory-warehouse.component.scss']
})
export class InventoryWarehouseComponent implements OnInit {


  public warehouses: any = [];

  constructor(private title: Title, public dialog: MatDialog, public apiService: ApiService) {
    this.title.setTitle("Inventario - Bodegas");
  }

  ngOnInit() {
    this.filterdata();
  }

  filterdata() {
    this.apiService.getWarehouses().subscribe((data:any) => {
      this.warehouses = data.data;
    });
  }
  addWarehouse() {
    let data = {
      type: 'add',
      name: ''
    };
    const dialogRef = this.dialog.open(InventoryWarehouseAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();      
    });
  }
  editWarehouse(index:number) {
    let data = this.warehouses[index];
    data.type = 'edit';
    const dialogRef = this.dialog.open(InventoryWarehouseAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();      
    });
  }

  deleteWarehouse(index:string) {
    let id = this.warehouses[index].id;
    let confirm = this.apiService.confirm("Confirmar","¿Deseas eliminar la bodega "+this.warehouses[index].name+"?");
    confirm.then((data:any)=> { 
      if (data.dismiss=="cancel") { }
      else if (data.value) {
        this.apiService.deleteCategory(id).subscribe((data:any)=>{
          if (data.res == "OK") {
            this.apiService.showOk("Perfecto",data.msg);
            this.warehouses.splice(index, 1);
          } else {
            this.apiService.showError("Error",data.msg);
          }
        });
      }
    });
  }
  

}
