import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { FileType } from './filetype';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { FiletypeService } from './filetype.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import * as XLSX from 'xlsx'; 
declare var $: any;

@Component({
  selector: 'app-filetype',
  templateUrl: './filetype.component.html',
  styleUrls: ['./filetype.component.css']
})
export class FiletypeComponent implements OnInit {

  sendMenuId: number;
  sendPageName = 'Filetype';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  filetypeForm: FormGroup;
  filetypes: FileType[] = [];
  filetypesactive: FileType[] = [];
  filetype: FileType;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  filetypeModalRef: BsModalRef;
  operation: string;
  userid: number;
  filetypeid: number;
  submitted = false;
  active: number;
  unamePattern: string;
  confmsg: string;
  p = 1;
  searchText: string;
  itemsPerPage = 10;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  showall = true;
  showallstatus = false;
  key = 'filetype';
  reverse = false;
  filetypesTOExport: any;
  storeData: any;     
  fileUploaded: File;  
  worksheet: any;  
  dataToImport: any;

  constructor(
    private filetypeservice: FiletypeService,
    private modalService: BsModalService,
    private formBuilder: FormBuilder,
    private router: Router,
    private toastr: ToastrService,
    private dialogService: DialogService
  ) {
     // get rights for the logged in user for the particular component
     if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('FileType_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('FileType_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
  } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('FileType_userRights');
  }
   }

  ngOnInit(): void {
    this.filetypeForm = this.formBuilder.group({
      filetypeid: [''],
      filetype: ['', [Validators.required]],
      icon: [''],
      active: ['']
    });
    this.searchText = '';
    this.showall = true;
    this.showallstatus = false;
    this.getAll();
this.getUserRights();
  }
 // function to get user rights
 getUserRights() {
  const btnToEnable = JSON.parse(this.actionRights);
  if (btnToEnable.length > 0) {
    this.readOnly = true;
    btnToEnable.forEach(d => {
      if (d !== undefined) {
        if (d === 2) {
          this.add = true;
        } else if (d === 3) {
          this.edit = true;
        } else if (d === 4) {
          this.delete = true;
        }
      }
    });
  }
}


  getactiveinactive(showallp) {
    this.filetypesactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.filetypes.forEach(data => {
        if (data.active === 1) {
          this.filetypesactive.push(data);
        }
      });
      this.filetypes = [];
      this.filetypes = this.filetypesactive;
    } else {
      this.showall = true;
      this.filetypes = [];
      this.getAll();
    }
  }


  clearForm() {
    this.filetypeModalRef.hide();
  }

  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }

  getAll() {
    this.filetypes = [];
    this.filetypesactive = [];
    this.filetypeservice.Get().subscribe(res => {
      this.filetypes = JSON.parse(res[0]);
      if (this.showallstatus === true) {
        this.filetypes.forEach(data => {
          if (data.active === 1) {
            this.filetypesactive.push(data);
          }
        });
        this.filetypes = [];
        this.filetypes = this.filetypesactive;
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }


  get g() { return this.filetypeForm.controls; }


  Post(filetype: FileType) {

    this.submitted = true;


    if ((filetype.filetype.trim() === undefined) || (filetype.filetype.trim() === '')) {
      this.toastr.error('Filetype should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    filetype.filetype = filetype.filetype.trim();
    if (this.operation === 'add') {
      filetype.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.filetypeservice.Post(filetype).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.filetypeModalRef.hide();
              this.getAll();
              this.toastr.success('Data added successfully');
              this.clearForm();
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    } else if (this.operation = 'update') {
      filetype.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.filetypeservice.Put(filetype).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {

            if (res.body !== 0) {
              this.filetypeModalRef.hide();
              this.getAll();
              this.toastr.success('Data updated successfully');
              this.clearForm();
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    }
    this.submitted = false;
  }

  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.filetypeForm.controls['active'].setValue(1);
    } else {
      this.filetypeForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(filetype, template: TemplateRef<any>) {
    if (filetype.active === 0) {
      this.confmsg = 'activate';
    } else {
      this.confmsg = 'deactivate'; }
     this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure you want to ' + this.confmsg + ' this record ?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.filetype = filetype;

          this.Delete();
        }
      });
  }

  Delete() {
    let msg;
    if (this.filetype.active === 0) {
      this.filetype.active = 1;
      msg = 'Record activated successfully';
    } else {
      this.filetype.active = 0;
      msg = 'Record deactivated successfully';
    }
    this.userid = +localStorage.getItem('userid');
    this.filetype.updatedby = this.userid;
    this.filetypeservice.Delete(this.filetype).subscribe(res => {
      this.toastr.success(msg);
      this.getAll();
    },
      error => { this.deleteResult = false; });

  }

  hidePopup() {
    this.filetypeModalRef.hide();
  }

  openFileTypeModal(template: TemplateRef<any>, type, filetype?: FileType) {

    this.operation = type;

    if (type === 'update') {
      this.filetypeForm.controls['filetypeid'].setValue(filetype.filetypeid);
      this.filetypeForm.controls['filetype'].setValue(filetype.filetype);
      this.filetypeForm.controls['icon'].setValue(filetype.icon);
      this.filetypeForm.controls['active'].setValue(filetype.active);
      this.filetype = filetype;
    }
    if (type === 'add') {
      this.filetypeForm.controls['filetypeid'].setValue(0);
      this.filetypeForm.controls['filetype'].setValue('');
      this.filetypeForm.controls['icon'].setValue('');
      this.filetypeForm.controls['active'].setValue(1);
    }
    this.filetypeModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
  exportToExcel() {
    this.filetypeservice.getToExport().subscribe(res => {
      
      if (res[0] !== undefined  && res[0] !== null &&  JSON.parse(res[0]).length  > 0) {
        this.filetypesTOExport = JSON.parse(res[0]);
        let today = new Date();
        let date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
        let time = today.getHours() + ":" + today.getMinutes() + ':' + today.getSeconds();
        let dateTime = date + ' ' + time;
        const wb: XLSX.WorkBook = XLSX.utils.book_new();
        const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.filetypesTOExport );
        const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
        const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        this.saveAsExcelFile(excelBuffer, 'File Type' + '-' + dateTime + '.xlsx');
      } else {
        this.toastr.error('No data to export');
         
      }
      }, err => { this.toastr.error(err);
         
      });
  }
  saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
    });
    var link = document.createElement('a');
    link.download = fileName;
    var url = window.URL.createObjectURL(data);
    link.href = url;
    document.body.appendChild(link);
    link.download = fileName;
    link.click();
    document.body.removeChild(link);
    self.close();
  }
  uploadData(event) {
    this.userid = +localStorage.getItem('userid');
    let files = $('#file-input').get(0).files;
      if (files.length !== 1) {
        throw new Error('Cannot use multiple files');
      } else {

        let readFile = new FileReader();  
        readFile.readAsArrayBuffer(files[0]); 
        readFile.onload = (e) => {  
          this.storeData = readFile.result;  
          let data = new Uint8Array(this.storeData);  
          let arr = new Array();  
          for (var i = 0; i != data.length; ++i) {
            arr[i] = String.fromCharCode(data[i]);  
          }
          let bstr = arr.join('');  
          let workbook = XLSX.read(bstr, { type: 'binary' });  
          let first_sheet_name = workbook.SheetNames[0];  
          this.worksheet = workbook.Sheets[first_sheet_name];           
          this.dataToImport = XLSX.utils.sheet_to_json(this.worksheet,{raw:true});
          this.dataToImport.forEach((i , index) => {
            this.dataToImport[index]['createdby'] = this.userid;
          });         
          //console.log(this.dataToImport);
          if(this.dataToImport.length > 0) {
            this.filetypeservice.dataToImport(this.dataToImport).subscribe(res => {
              if (res.body !== undefined && res.body !== null) {
              if (res.body === -1) {
                this.toastr.error('Duplicate values found in the excel');
               } else if (res.body === 1) {
                   this.toastr.success('Data imported successfully');
                   $('#file-input')[0].value = ''; 
                  this.getAll();
                }
              }
            }, err => { this.toastr.error(err); });
          }
         

      
    }    
   
    }
  }
}
