import { Component, OnInit } from '@angular/core';
 
import { LocalDataSource } from 'ng2-smart-table';
import { SmartTableData } from '../../@core/data/smart-table';
import { PageapiService } from '../pageapi.service';
import { NbComponentStatus, NbGlobalPhysicalPosition, NbGlobalPosition, NbToastrService, NbWindowControlButtonsConfig, NbWindowRef, NbWindowService } from '@nebular/theme';
import { ProductFormComponent } from './product-form/product-form.component';
 
@Component({
  selector: 'ngx-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.scss']
})
export class ProductComponent  {
  settings = {
    actions: {
      
      position: 'right', // left|right
    },
    mode: 'external',
    add: {
      addButtonContent: '<i class="nb-plus"></i>',
      createButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      index: {
        title: 'ID',
        type: 'number',
      },
      productName: {
        title: 'Product Name',
        type: 'string',
      },
      productCategory: {
        title: 'Product Category',
        type: 'string',
      },
      productType: {
        title: 'Product Type',
        type: 'string',
      },
      description: {
        title: 'Description',
        type: 'string',
      },
     
    },
  };
  product:any =[];
  source: LocalDataSource = new LocalDataSource();
  minimize = false;
  maximize = false;
  fullScreen = true;
  close = true;
  formData:any=[]
  index = 1;
  destroyByClick = true;
  duration = 2000;  filteredItems: any[];
  searchTerm: string;
  hasIcon = true;
  position: NbGlobalPosition = NbGlobalPhysicalPosition.TOP_RIGHT;
  preventDuplicates = false;
  status: NbComponentStatus = 'primary';
  constructor(private toastrService: NbToastrService,private service: SmartTableData,public _api:PageapiService,private windowService: NbWindowService) {
    const data = this.service.getData();
  
    this.getProductlistApi()

   
    
  }

  onDeleteConfirm(event): void {
    console.log(event)
    let passData = event
    //if (window.confirm('Are you sure you want to delete?')) {
      //event.confirm.resolve();

   

      let deletedata  = {'isActive':event.isActive,'id':passData.id}
  
      this._api.CreateProductDetails (deletedata).subscribe(res => {
        if (res.status == 200) {
  console.log(res)
  this.getProductlistApi();
  if(event.isActive == 1){
    this.showToast('success', 'Data Removed Successfully', 'Active Product Data Completed..!');
  }else{
    this.showToast('success', 'Data Removed Successfully', 'Inactive Product Data Completed..!');
  }

 // this.showToast('success', 'Data Removed Successfully', 'Removed Product Data Completed..!');
  event.confirm.resolve();
        }else{
          this.showToast('warning', 'Somthing is Wrong...!', 'Edit Product Data Failed..!');
        }
      })

    // } else {
    //   event.confirm.reject();
    // }
  }
  onCreateConfirm() {
    console.log("Create Event In Console")
   // console.log(event);
    // const buttonsConfig: NbWindowControlButtonsConfig = {
    //   minimize: this.minimize,
    //   maximize: this.maximize,
    //   fullScreen: this.fullScreen,
    //   close: this.close,
    // };
    // let config= {
    //   hasBackdrop: true,
    //   width: '500px',
    //   height: '300px',
    // }
    // const windowRef: NbWindowRef =  this.windowService.open(ProductFormComponent, { title: `New Product`, buttons: buttonsConfig , });
   
    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    let config= {
      hasBackdrop: true,
      width: '500px',
      height: '300px',
    }
    let data:any = {action:'Add'}
    
    const windowRef: NbWindowRef =  this.windowService.open(ProductFormComponent, { title: `New Product`, buttons: buttonsConfig ,context: data });

      // Subscribe to the afterClosed event
      windowRef.onClose.subscribe((data) => {
        // Handle the window closure
        console.log(data);
        if(data == 1){
          this.showToast('success', 'Data Saved Successfully', 'Add Product Data Completed..!');
          this.getProductlistApi();
           console.log('Window closed 123');
        }else if(data == 0){
          this.showToast('warning', 'Somthing is Wrong...!', 'Add Product Data Failed..!');
        }
      });
  }

  onSaveConfirm(event) {
    console.log("Edit Event In Console")
    console.log(event);
    // event = {action:'Edit'}
    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    const windowRef: NbWindowRef =  this.windowService.open(ProductFormComponent, { title: `Edit Product`, context: event
    , buttons: buttonsConfig  });
   


      // Subscribe to the afterClosed event
      windowRef.onClose.subscribe((data) => {
        // Handle the window closure
        console.log(data);
        if(data == 1){
          this.showToast('success', 'Data Changed Successfully', 'Edit Product Data Completed..!');
          this.getProductlistApi();
           console.log('Window closed 123');
        }else if(data == 0){
          this.showToast('warning', 'Somthing is Wrong...!', 'Edit Product Data Failed..!');
        }
       
      
      });
  }


  getProductlistApi(){
    let param ={}
    this._api.getProducts(param).subscribe(res => {
      console.log(res)
      if(res.status == 200){

       let passData =  res.data
       let product = passData 

       product.forEach((element:any, index) => {
        element.index = index  +1       
        
      });
      this.product = product
      //  console.log(data)
       // this.source.load(product);
      }else{
        this.source.load([]);
      }
    })
  }


  private showToast(type: NbComponentStatus, title: string, body: string) {
    const config = {
      status: type,
      destroyByClick: this.destroyByClick,
      duration: this.duration,
      hasIcon: this.hasIcon,
      position: this.position,
      preventDuplicates: this.preventDuplicates,
    };
    const titleContent = title ? ` ${title}` : '';

    this.index += 1;
    this.toastrService.show(
      body,
      `${titleContent}`,
      config);
  }
  filterItems() {
    console.log(  this.searchTerm)
   
     if(  this.searchTerm !=''){
   
   
     this.filteredItems = this.product.filter(item =>
       Object.values(item).some(value => {
         if (typeof value === 'string') {
           return value.toLowerCase().includes(this.searchTerm.toLowerCase());
         }
         return false;
       })
     );
     this.product = this.filteredItems
   }else{
     console.log( 'fhjsgsajdhgasksjgfcckjsdfgckjsdhfk')  
   
     this.getProductlistApi()
   }
   
   
   
   console.log( this.filteredItems)
   }
}
