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

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

  public categories: any = [];

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


  ngOnInit() {
    this.filterdata();
  }

  filterdata() {
    this.apiService.getCategories().subscribe((data:any) => {
      this.categories = data.data;
    });
  }
  addCategory() {
    let data = {
      type: 'add',
      name: '',
      parent: '',
      banner: ''
    };
    const dialogRef = this.dialog.open(CatalogCategoryAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();      
    });
  }
  editCategory(index:number) {
    let data = this.categories[index];
    data.type = 'edit';
    const dialogRef = this.dialog.open(CatalogCategoryAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();      
    });
  }

  deleteCategory(index:string) {
    let id = this.categories[index].id;
    let confirm = this.apiService.confirm("Confirmar","¿Deseas eliminar la categoria "+this.categories[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.categories.splice(index, 1);
          } else {
            this.apiService.showError("Error",data.msg);
          }
        });
      }
    });
  }
  

}
