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 { autoarchivejob_model } from './autoarchivejob_model';
import { AutoarchivejobService } from './autoarchivejob.service';

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


  p = 1; public searchText: string;
  operation:any;
  itemsPerPage = 10;
  autoarchivejobModalRef: BsModalRef;
  autoarchivejobForm: FormGroup;
  autoarchive_data: autoarchivejob_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 = 'errortype';
  autoarchivejobactive:autoarchivejob_model[]=[];
  reverse = false;
  autoarchivejoblst:autoarchivejob_model[]=[];
  constructor(
    private router: Router,
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private SpinnerService: NgxSpinnerService,
    private dashboardservice: DashboardService,
    private dialogService: DialogService,
    private toastr: ToastrService,
    private autoarchivejob_service: AutoarchivejobService) {  
    // get rights for the logged in user for the particular component
      
      if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Error_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Error_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Error_userRights');
    }
  }

  ngOnInit(): void {
    this.autoarchivejobForm = this.formBuilder.group({
      autoarchivejobid: [''],
      jobtype: [0, [Validators.required]],
      intervaltype: [0, [Validators.required]],
      intervalvalue: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.onload();

  }
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  
  clearForm(){
    this.autoarchivejobForm.controls['autoarchivejobid'].setValue(0)
      this.autoarchivejobForm.controls['jobtype'].setValue(0);
      this.autoarchivejobForm.controls['intervaltype'].setValue(0);
      this.autoarchivejobForm.controls['intervalvalue'].setValue('');
      this.autoarchivejobForm.controls['active'].setValue(0);
      this.autoarchivejobModalRef.hide();
      this.add=false;
      this.edit=false;
  }

  onload(){
    this.autoarchivejob_service.Get_all().subscribe(res => {
      debugger;
      if(res.body != null && res.body != undefined){
        this.autoarchivejoblst = res.body;
        }
       this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting Archive Job data');
    });
  }

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

    this.autoarchivejob_service.Active_AutoArchiveJob(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.autoarchivejobactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.autoarchivejoblst.forEach(data => {
        if (data.active === 1) {
          this.autoarchivejobactive.push(data);
        }
      });
      this.autoarchivejoblst = [];
      this.autoarchivejoblst = this.autoarchivejobactive;
    } else {
      this.showall = true;
      this.autoarchivejoblst = [];
      this.onload();
    }
    this.SpinnerService.hide();
  }

  Post(item:autoarchivejob_model){
debugger;
if(this.autoarchivejobForm.valid){
  if(Number(item.intervaltype) == 0 && Number(item.jobtype) == 0){
    this.toastr.error('Please select the required Fields')
    return;
  }

  if(this.operation==='add'){
    if(this.autoarchivejoblst.length != 0){
      let key = this.autoarchivejoblst.findIndex(x=>x.jobtype == item.jobtype);
        if(key != -1){
          this.toastr.error(item.jobtype + ' Already existed.');
          return;
        }
    }
    var inputData = [];
    inputData.push({
      jobtype: item.jobtype,
      intervaltype: item.intervaltype,
      intervalvalue: Number(item.intervalvalue),
      createdby: Number(localStorage.getItem('userid')),
      active:1
    });

    this.autoarchivejob_service.Add_AutoArchiveJob(inputData[0]).subscribe(res => {
      debugger;
      this.autoarchivejobModalRef.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({
      autoarchivejobid :item.autoarchivejobid,
      jobtype: item.jobtype,
      intervaltype: item.intervaltype,
      intervalvalue: Number(item.intervalvalue),
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
    });

    this.autoarchivejob_service.Edit_AutoArchiveJob(inputData[0]).subscribe(res => {
      debugger;
      this.autoarchivejobModalRef.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.autoarchivejobForm.controls['active'].setValue(1);
    } else {
      this.autoarchivejobForm.controls['active'].setValue(0);
    }
  }
  openCheckListModal(template: TemplateRef<any>, type, item?: autoarchivejob_model) {
debugger;
    this.operation = type;

    if (type === 'update') {
      this.autoarchivejobForm.controls['autoarchivejobid'].setValue(item.autoarchivejobid);
      this.autoarchivejobForm.controls['jobtype'].setValue(item.jobtype);
      this.autoarchivejobForm.controls['intervaltype'].setValue(item.intervaltype);
      this.autoarchivejobForm.controls['intervalvalue'].setValue(item.intervalvalue);
      this.autoarchivejobForm.controls['active'].setValue(item.active);
      this.add=false;
      this.edit=true;

    this.autoarchive_data = item;
    }
    if (type === 'add') {
      this.autoarchivejobForm.controls['jobtype'].setValue(0);
      this.autoarchivejobForm.controls['intervalvalue'].setValue('');
      this.autoarchivejobForm.controls['intervaltype'].setValue(0);
      this.autoarchivejobForm.controls['active'].setValue(0);
      this.edit=false;
      this.add=true;
    }
    this.autoarchivejobModalRef = this.modalService.show(template, this.config);

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


}
