import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { AlertModalComponent } from '../alert-modal/alert-modal.component';
import { OpenImageComponent } from '../open-image/open-image.component';
import { WidgetService } from 'src/app/service/widgets.service';
import { WidgetModel } from 'src/app/model/widgets.model';
declare var require: any
const FileSaver = require('file-saver');
@Component({
  selector: 'app-view-list-widgets',
  templateUrl: './view-list-widgets.component.html',
  styleUrls: ['./view-list-widgets.component.scss']
})
export class ViewListWidgetsComponent implements OnInit {
  page = 1;
  pageSize = 10;
  listWidget:WidgetModel[]=[]
  search:string = ''

  constructor(private modalService: NgbModal,private widgetService:WidgetService) {
  }
  openEmployeeModal(image:string) {
    const modalRef = this.modalService.open(OpenImageComponent, {
      centered: true,
      windowClass: 'my-dialog-img-preview'
    })
    modalRef.componentInstance.linkImage = image
    modalRef.result.then(result => {
    }, reason => {
      this.modalService.dismissAll()
    })
  }

  async downloadFile(logId:string){
    try {
      const data = await this.widgetService.downloadFile(logId).toPromise();
      if(data){
        FileSaver.saveAs(new Blob([data]), "file_download.xlsx");
      }
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  getStatus(status: string) {
    if (status == '0') {
      return 'Private'
    } else if (status == '1') {
      return 'Public'
    } 
  }
  filterListWidget(){
    return this.listWidget.filter(x => x.widgetTname.toLowerCase().includes(this.search.toLowerCase())||x.widgetEname.toLowerCase().includes(this.search.toLowerCase()))
  }
  async getListExcel(){
    try {
      const data = await this.widgetService.getListWidgets().toPromise();
      this.listWidget = data.map(x => new WidgetModel(x))
    } catch (error) {
      console.error('Error loading data:', error);
    }
  }
  ngOnInit() {
    this.getListExcel();
  }
  openLink(url:string){
    window.open(url, "_blank");
  }


  openAlertModal(message?: string) {
    const modalRef = this.modalService.open(AlertModalComponent, {
      centered: true,
      backdrop: 'static'
    })
    modalRef.componentInstance.message = message ? message : ""
    modalRef.result.then(result => {
      this.modalService.dismissAll()
    }, reason => {
      this.modalService.dismissAll()
    })
  }
  coverDate(date:string){
  return  date.split('-').reverse().join('/')
  }
}
