import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Router } from '@angular/router';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { MailField } from './mailfield';
import { MailFieldService } from './mailfield.service';

@Component({
  selector: 'app-mailfield',
  templateUrl: './mailfield.component.html',
  styleUrls: ['./mailfield.component.css']
})
export class MailfieldComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'MailField';

  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly: boolean; add: boolean; edit: boolean; delete: boolean;
  mailfieldForm: FormGroup;
  mailfields: MailField[] = [];
  mailfieldsactive: MailField[] = [];
  mailfield: MailField;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  mailfieldModalRef: BsModalRef;
  operation: string;
  userid: number;
  mailfieldid: 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 = 'mailfield';
  reverse = false;

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

  }

  ngOnInit() {
    this.mailfieldForm = this.formBuilder.group({
      mailfieldid: [''],
      mailfieldname: ['', [Validators.required]],
      mailfieldvalue: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.getAll();

    // for action rights
    this.readOnly = true;
    this.add = true;
    this.edit = true;
    this.delete = true;
    this.submitShow = true;
    // this.getActionRightsList();
  }
 // 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.mailfieldsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.mailfields.forEach(data => {
        if (data.active === 1) {
          this.mailfieldsactive.push(data);
        }
      });
      this.mailfields = [];
      this.mailfields = this.mailfieldsactive;
    } else {
      this.showall = true;
      this.mailfields = [];
      this.getAll();
    }
  }

  // assigning value from menu rights button
  getActionRightsList() {
    const btnToEnable = JSON.parse(this.actionRights);
    if (btnToEnable.length > 0) {
      btnToEnable.forEach(d => {
        if (d !== undefined) {
          if (d === 1) {
            this.readOnly = true;
          } else if (d === 2) {
            this.readOnly = true;
            this.add = true;
            this.submitShow = true;
          } else if (d === 3) {
            this.readOnly = true;
            this.edit = true;
            // this.submitShow = true;
          } else if (d === 4) {
            this.readOnly = true;
            this.delete = true;
          }
        }
      });
    }
  }

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

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


  getAll() {
    this.mailfields = [];
    this.mailfieldsactive = [];
    this.mailfieldservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.mailfields = JSON.parse(res[0]);
        if (this.showallstatus === true) {
          this.mailfields.forEach(data => {
            if (data.active === 1) {
              this.mailfieldsactive.push(data);
            }
          });
          this.mailfields = [];
          this.mailfields = this.mailfieldsactive;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(mailfield: MailField) {

    this.submitted = true;

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

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    mailfield.mailfieldname = mailfield.mailfieldname.trim();
    if (this.operation === 'add') {

      mailfield.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.mailfieldservice.Post(mailfield).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.mailfieldModalRef.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') {
      this.submitShow = true;
      mailfield.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.mailfieldservice.Put(mailfield).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
if (res.body !== 0) {
              this.mailfieldModalRef.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.mailfieldForm.controls['active'].setValue(1);
    } else {
      this.mailfieldForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(mailfield, template: TemplateRef<any>) {
    if (mailfield.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.mailfield = mailfield;

          this.Delete();

        }

      });

  }

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

  }

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

  openMailFieldModal(template: TemplateRef<any>, type, mailfield?: MailField) {

    this.operation = type;

    if (type === 'update') {
      this.mailfieldForm.controls['mailfieldid'].setValue(mailfield.mailfieldid);
      this.mailfieldForm.controls['mailfieldname'].setValue(mailfield.mailfieldname);
      this.mailfieldForm.controls['mailfieldvalue'].setValue(mailfield.mailfieldvalue);
      this.mailfieldForm.controls['active'].setValue(mailfield.active);
      this.mailfield = mailfield;
    }
    if (type === 'add') {
      this.mailfieldForm.reset();
      this.mailfieldForm.controls['mailfieldid'].setValue(0);
      this.mailfieldForm.controls['active'].setValue(1);
    }
    this.mailfieldModalRef = this.modalService.show(template, this.config);

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

  }
  omitspecialchar(event) {
    let k;
    k = event.charCode;  // k = event.keyCode;  (Both can be used)
    return((k > 64 && k < 91) || (k > 96 && k < 123) || k === 8 || k === 32 || (k >= 48 && k <= 57));
 }

}
