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 { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import { ToastrService } from 'ngx-toastr';
import { DashboardService } from 'src/app/dashboard/dashboard.service';
import { State_code } from './statecode';
import { StatecodeService } from './statecode.service';

@Component({
  selector: 'app-statecode',
  templateUrl: './statecode.component.html',
  styleUrls: ['./statecode.component.css']
})
export class StatecodeComponent implements OnInit {
  p = 1; public searchText: string;
  operation:any;
  itemsPerPage = 10;
  statecodeModalRef: BsModalRef;
  statecodeForm: FormGroup;
  statecode: State_code;
  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 = 'statename';
  statecodeactive :State_code[] =[];
  reverse = false;
  statecodelst:State_code[]=[];
  constructor(private statecode_service:StatecodeService,
    private router: Router,
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private SpinnerService: NgxSpinnerService,
    private dashboardservice: DashboardService,
    private dialogService: DialogService,
    private toastr: ToastrService) { 
      debugger;
      if (this.router.getCurrentNavigation().extras.state !== undefined) {
        localStorage.setItem('Statecode_menuid', this.router.getCurrentNavigation().extras.state.menuid);
        localStorage.setItem('Statecode_userRights', this.router.getCurrentNavigation().extras.state.action);
        this.actionRights = [];
        this.actionRights = this.router.getCurrentNavigation().extras.state.action;
      } else {
        this.actionRights = [];
        this.actionRights = localStorage.getItem('Statecode_userRights');
      }
    }

  ngOnInit(): void {
    this.statecodeForm = this.formBuilder.group({
      statecodeid: [''],
      statename: ['', [Validators.required]],
      stateabbreviation:['',[Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.onload();
  }
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  
  clearForm(){
    this.statecodeForm.controls['statecodeid'].setValue(0)
      this.statecodeForm.controls['statename'].setValue('');
      this.statecodeForm.controls['stateabbreviation'].setValue('');
      this.statecodeForm.controls['active'].setValue(0);
      this.statecodeModalRef.hide();
      this.add=false;
      this.edit=false;
  }

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

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

  OpenConfirmTemplate(item: State_code) {
    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:State_code){
    var inputData = [];
    inputData.push({
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
      statecodeid:item.statecodeid
    })

    this.statecode_service.Active_statecode(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);
  });
  }

  Post(statecode:State_code){
debugger;
if(this.statecodeForm.valid){

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

    this.statecode_service.Add_statecode(inputData[0]).subscribe(res => {
      debugger;
      this.statecodeModalRef.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({
      statecodeid :statecode.statecodeid,
      statename: statecode.statename,
      updatedby: Number(localStorage.getItem('userid')),
      active:statecode.active,
      stateabbreviation: statecode.stateabbreviation,
    });

    this.statecode_service.Edit_statecode(inputData[0]).subscribe(res => {
      debugger;
      this.statecodeModalRef.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.statecodeForm.controls['active'].setValue(1);
    } else {
      this.statecodeForm.controls['active'].setValue(0);
    }
  }
  openCheckListModal(template: TemplateRef<any>, type, statecode?: State_code) {
debugger;
    this.operation = type;

    if (type === 'update') {
      this.statecodeForm.controls['statecodeid'].setValue(statecode.statecodeid);
      // this.checklistForm.controls['checklistid'].setValue(checklistdetails.checklistid);
      this.statecodeForm.controls['statename'].setValue(statecode.statename);
      this.statecodeForm.controls['stateabbreviation'].setValue(statecode.stateabbreviation);
      this.statecodeForm.controls['active'].setValue(statecode.active);
      this.add=false;
      this.edit=true;

    this.statecode = statecode;
    }
    if (type === 'add') {
      this.statecodeForm.controls['statecodeid'].setValue(0)
      this.statecodeForm.controls['statename'].setValue('');
      this.statecodeForm.controls['stateabbreviation'].setValue('');
      this.statecodeForm.controls['active'].setValue(0);
      this.edit=false;
      this.add=true;
    }
    this.statecodeModalRef = this.modalService.show(template, this.config);

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


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