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

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

  public products: any = [];
  public filter: any = { name: '', type: '' }
  public types: any = [];
  public categories: any = [];

  constructor(private title: Title, public dialog: MatDialog, public apiService: ApiService) {
    this.title.setTitle("Catálogo - Productos");
  }


  ngOnInit() {
    this.filterdata();
  }

  filterdata() {
    this.apiService.getProducts(this.filter.name, this.filter.type).subscribe((data:any) => {
      this.products = data.data;
    });
  }
  addProduct() {
    let data = {
      type: 'add',
      name: '',
      description: '',
      type_sale: '',
      stock_sale: 0,
      stock_ordered: 0,
      cost: 0,
      price: 0,
      price_sale: 0,
      min_order: 0,
      max_order: 0,
      status: 0,
      image: '',
      cbd: '',
      thc: '',
      categories: []
    };
    const dialogRef = this.dialog.open(CatalogProductsAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();      
    });
  }
  editProduct(index:number) {
    let data = this.products[index];
    data.type = 'edit';
    const dialogRef = this.dialog.open(CatalogProductsAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();      
    });
  }

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

}
