import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material';
import { Router } from '@angular/router';
import { DialogService } from 'ng2-bootstrap-modal';
import { BsModalRef, BsModalService, ModalOptions } from 'ngx-bootstrap';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { DashboardService } from 'src/app/dashboard/dashboard.service';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { StatecodeService } from '../statecode/statecode.service';
import { FrequencyService } from './frequency.service';
import { frequency_model } from './frequency_model';

@Component({
  selector: 'app-frequency',
  templateUrl: './frequency.component.html',
  styleUrls: ['./frequency.component.css']
})
export class FrequencyComponent implements OnInit {
  p = 1; public searchText: string;
  operation:any;
  itemsPerPage = 10;
  frequencyModalRef: BsModalRef;
  frequencyForm: FormGroup;
  frequency_data: frequency_model;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  showall = true;
  showallstatus = false;
  actionRights: any; _menuId: any; readOnly: boolean; add: boolean =true; edit: boolean =true; delete: boolean; submitShow: boolean;
  useridnew: string = localStorage.getItem('userid');
  key = 'frequencytype';
  frequencyactive:frequency_model[]=[];
  reverse = false;
  frequencylst:frequency_model[]=[];
  constructor(private frequency_service:FrequencyService,
    private router: Router,
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private SpinnerService: NgxSpinnerService,
    private dashboardservice: DashboardService,
    private dialogService: DialogService,
    private toastr: ToastrService) {  
    // get rights for the logged in user for the particular component
      
      if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Frequency_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Frequency_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Frequency_userRights');
    }
  }

  ngOnInit(): void {
    this.frequencyForm = this.formBuilder.group({
      frequencyid: [''],
      frequencytype: ['', [Validators.required]],
      frequencyabbreviation:['',[Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.onload();

  }
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  
  clearForm(){
    this.frequencyForm.controls['frequencyid'].setValue(0)
      this.frequencyForm.controls['frequencytype'].setValue('');
      this.frequencyForm.controls['frequencyabbreviation'].setValue('');
      this.frequencyForm.controls['active'].setValue(0);
      this.frequencyModalRef.hide();
      this.add=false;
      this.edit=false;
  }

  onload(){
    this.frequency_service.Get_all().subscribe(res => {
      debugger;
     // var demo = JSON.parse(res[0]);
    //  console.log(demo);

      this.frequencylst = res.body;
     // console.log(this.statecodelst);
      // console.log(this.mailfolderlst.length);
     // this.originallst =JSON.parse(res.body);
       this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting State code data');
    });
  }

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

      });
  }

  Delete(item:frequency_model){
    debugger;
    var inputData = [];
    inputData.push({
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
      frequencyid:item.frequencyid
    })

    this.frequency_service.Active_frequency(inputData[0]).subscribe(res => {
      debugger;
      if(item.active == 0){
        this.toastr.success('Inactive the record successfully');
        
      }else{
        this.toastr.success('Active the record successfully');
      }
      this.onload();
  }, error => {
      this.toastr.error(error.error);
  });
  }

  getactiveinactive(showallp) {
    this.SpinnerService.show();
    this.frequencyactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.frequencylst.forEach(data => {
        if (data.active === 1) {
          this.frequencyactive.push(data);
        }
      });
      this.frequencylst = [];
      this.frequencylst = this.frequencyactive;
    } else {
      this.showall = true;
      this.frequencylst = [];
      this.onload();
    }
    this.SpinnerService.hide();
  }

  Post(item:frequency_model){
debugger;
if(this.frequencyForm.valid){

  if(this.operation==='add'){
    var inputData = [];
    inputData.push({
      frequencytype: item.frequencytype,
      createdby: Number(localStorage.getItem('userid')),
      active:1,
      frequencyabbreviation: item.frequencyabbreviation,
    });

    this.frequency_service.Add_frequency(inputData[0]).subscribe(res => {
      debugger;
      this.frequencyModalRef.hide();
      this.toastr.success('Successfully Added.');
      this.onload();
     //this.user_option=false;
    
  }, error => {
      this.toastr.error(error.error);
  });
  }else if(this.operation ==='update'){
    var inputData = [];
    inputData.push({
      frequencyid :item.frequencyid,
      frequencytype: item.frequencytype,
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
      frequencyabbreviation: item.frequencyabbreviation,
    });

    this.frequency_service.Edit_frequency(inputData[0]).subscribe(res => {
      debugger;
      this.frequencyModalRef.hide();
      this.toastr.success('Successfully Updated.');
this.onload();
     //this.user_option=false;
    
  }, error => {
      this.toastr.error(error.error);
  });

  }

}else{
  this.toastr.error('Please fill the Required fields.');

}

  }

  

  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.frequencyForm.controls['active'].setValue(1);
    } else {
      this.frequencyForm.controls['active'].setValue(0);
    }
  }
  openCheckListModal(template: TemplateRef<any>, type, item?: frequency_model) {
debugger;
    this.operation = type;

    if (type === 'update') {
      this.frequencyForm.controls['frequencyid'].setValue(item.frequencyid);
      // this.checklistForm.controls['checklistid'].setValue(checklistdetails.checklistid);
      this.frequencyForm.controls['frequencytype'].setValue(item.frequencytype);
      this.frequencyForm.controls['frequencyabbreviation'].setValue(item.frequencyabbreviation);
      this.frequencyForm.controls['active'].setValue(item.active);
      this.add=false;
      this.edit=true;

    this.frequency_data = item;
    }
    if (type === 'add') {
      this.frequencyForm.controls['frequencytype'].setValue('');
      this.frequencyForm.controls['frequencyabbreviation'].setValue('');
      this.frequencyForm.controls['active'].setValue(0);
      this.edit=false;
      this.add=true;
    }
    this.frequencyModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
}
