import { Component, OnInit, ElementRef, ViewChild, TemplateRef } from '@angular/core';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import { DialogService } from 'ng2-bootstrap-modal';
declare var $: any;
import { MailTemplate } from './mailtemplate';
import { MailtemplateService } from './mailtemplate.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Richtext } from 'dhx-richtext';
import { MailFieldService } from '../mailfield/mailfield.service';


@Component({
  selector: 'app-mailtemplate',
  templateUrl: './mailtemplate.component.html',
  styleUrls: ['./mailtemplate.component.css']
})
export class MailtemplateComponent implements OnInit {
  // text box focus variable
  @ViewChild('txtMailTemplateName', { static: false }) myTxtMailTemplateName: ElementRef;

  // grid search variables
  searchText: string;

  // pagination variables
  p = 1;
  itemsPerPage = 10;

  // other variables
  _mailTemplateList: any = [];
  _mailTemplateListTmp: any = [];
  _mailTemplateListactive: any = [];
  showallstatus = false;
  showall = true;
  operation: string;
  textBoxTouched: boolean;
  _mailTemplateId: any;
  action: string;
  currentEmailTemplate: string;
  _mailFieldList: any;
  isViewMode = false;

  // form variables
  mailTemplateForm: FormGroup;
  mailTemplates: MailTemplate[] = [];
  mailTemplateactive: MailTemplate[] = [];
  MailTemplate: MailTemplate;
  submitted = false;

  // template variables
  mailTemplateModalRef: BsModalRef;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };

  // variable for logged in user id
  public userid: number;

  // rich textbox variables
  public richtext: any;

  // sorting variables
  key = 'Template Name'; // set default
  reverse = false;

  // variables for alert message variables
  confmsg: string;
  msg: string;

  // form action rights varaibales
  actionRights: any;
  readOnly = false;
  add = false;
  edit = false;
  delete = false;

  constructor(
    private router: Router,
    private toastr: ToastrService,
    private mailtemplateService: MailtemplateService,
    private formBuilder: FormBuilder,
    private dialogService: DialogService,
    private SpinnerService: NgxSpinnerService,
    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('MailTemplate_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('MailTemplate_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('MailTemplate_userRights');
    }
  }

  ngOnInit(): void {
    this.mailTemplateForm = this.formBuilder.group({
      mailtemplatename: ['', [Validators.required]],
      subject: ['', [Validators.required]],
      active: ['']
    });
    this.action = 'add';
    this._mailTemplateId = '';
    this.textBoxTouched = false;
    this.currentEmailTemplate = '';
    this.loadExisitingMailTemplateList();
    this.loadMailFieldList();
    this.getUserRights();
  }

  // method to get the existing list of email templates
  loadExisitingMailTemplateList() {
    this.SpinnerService.show();
    this._mailTemplateList = [];
    this._mailTemplateListactive = [];
    this._mailTemplateListTmp = [];
    this.mailtemplateService.Get().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this._mailTemplateListTmp = JSON.parse(res[0]);
          this._mailTemplateListTmp.forEach(item => {
            if (item.mailtemplateid !== 0) {
              // pushing the required fields to the list to bind in the grid
              this._mailTemplateList.push({
                mailtemplateid: item.mailtemplateid,
                mailtemplatename: item.mailtemplatename,
                active: item.active,
                createdbyname:item.createdbyname,
                createdon:item.createdon,
                updatedbyname:item.updatedbyname,
                updatedon:item.updatedon
              });
            }
          });
          if (this.showallstatus === true) {
            this._mailTemplateList.forEach(data => {
              if (data.active === 1) {
                this._mailTemplateListactive.push(data);
              }
            });
            this._mailTemplateList = [];
            this._mailTemplateList = this._mailTemplateListactive;
          }
        }
      }
      this.SpinnerService.hide();
    }, error => { this.SpinnerService.hide(); this.toastr.error('Error while getting data'); });
  }

  // get show all active function
  getActiveInactive(showallp) {
    this._mailTemplateListactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this._mailTemplateList.forEach(data => {
        if (data.active === 1) {
          this._mailTemplateListactive.push(data);
        }
      });
      this._mailTemplateList = [];
      this._mailTemplateList = this._mailTemplateListactive;
    } else {
      this.showall = true;
      this._mailTemplateList = [];
      this.loadExisitingMailTemplateList();
    }
  }

  // method to show the pop up
  openMailTemplateModal(template: TemplateRef<any>, type, mailTemplate?: MailTemplate) {
    this.operation = type;
    if (type === 'update') {
      this.mailTemplateForm.controls['mailtemplateid'].setValue(mailTemplate.mailtemplateid);
      this.mailTemplateForm.controls['mailtemplatename'].setValue(mailTemplate.mailtemplatename);
      this.mailTemplateForm.controls['active'].setValue(mailTemplate.active);
      this.MailTemplate = mailTemplate;
    }
    if (type === 'add') {
      this.mailTemplateForm.controls['mailtemplateid'].setValue(0);
      this.mailTemplateForm.controls['mailtemplatename'].setValue('');
      this.mailTemplateForm.controls['active'].setValue(1);
    }
    this.mailTemplateModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }

  // method to validate the richtext container touched or not
  touched() {
    this.textBoxTouched = true;
  }

  // function to load the rich text box container
  loadRichTextBox() {
    this.richtext = new Richtext('richtext_container', {
      mode: 'classic', toolbarBlocks: ['default']
    });
    this.richtext.toolbar.data.remove('link');
    this._mailFieldList = this._mailFieldList.filter(item => item.active === 1);
    for (let i = 0; i < this._mailFieldList.length; i++) {
      const _value = this._mailFieldList[i]['mailfieldname'];
      const _id = this._mailFieldList[i]['mailfieldvalue'];
      this.richtext.toolbar.data.add(
        {
          type: 'button',
          value: _value,
          id: _id
        }, i + 24);
    }
    const EditorAPI = this.richtext.getEditorAPI();
    this.richtext.toolbar.events.on('click', function (id, event) {
      if (id.startsWith('$$')) {
        EditorAPI.add(' ' + id + ' ');
      }
      event.preventDefault();
    });
    this.richtext.toolbar.events.on('selectionRefresh', function (event) {
      event.preventDefault();
    });

  }
  // function to sort the list
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }

  // saving the mail template details in to the db
  saveTemplate(operation) {
    this.submitted = true;
    this.userid = +localStorage.getItem('userid');
    const validmailContentTxt = this.richtext.getValue('markdown');
    const mailContentTxt = this.richtext.getValue('html');
    if (this.mailTemplateForm.valid) {

      if (this.mailTemplateForm.value.mailtemplatename.trim() == null || this.mailTemplateForm.value.mailtemplatename.trim() === '') {
        this.toastr.warning('Mail template should not be empty');
        return;
      }
      if (this.mailTemplateForm.value.subject.trim() == null || this.mailTemplateForm.value.subject.trim() === '') {
        this.toastr.error('Subject should not be empty');
        return;
      }

      if ((mailContentTxt.trim() === undefined) || (mailContentTxt.trim() === '') ||
      (mailContentTxt.trim() === '<p></p>') || (validmailContentTxt.trim() === '')) {
        this.toastr.error('Mail content should not be empty');
        return;
      }
      this.mailTemplateForm.value.body = mailContentTxt;
      if ((mailContentTxt.trim() !== undefined) || (mailContentTxt.trim() !== '')) {
        if (operation === 'add') {
          this.SpinnerService.show();
          this.mailTemplateForm.value.active = 1;
          this.mailTemplateForm.value.createdby = this.userid;
          this.mailtemplateService.Post(this.mailTemplateForm.value).subscribe(
            (res) => {
              if (res.body !== 0) {
                this.SpinnerService.hide();
                this.toastr.success('Data added successfully');
                this.loadExisitingMailTemplateList();
                this.clearForm();

              } else {
                this.SpinnerService.hide();
                this.toastr.warning('Mail Template exists already');
              }

            }, error => {
              this.SpinnerService.hide();
              this.toastr.error(error);
            });
        }
        if (operation === 'update') {
          this.SpinnerService.show();
          this.mailTemplateForm.value.updatedby = this.userid;
          this.mailTemplateForm.value.mailtemplateid = this._mailTemplateId;
          this.mailtemplateService.Put(this.mailTemplateForm.value).subscribe(
            (res) => {
              if (res.body !== 0) {
                this.SpinnerService.hide();
                this.toastr.success('Data updated successfully');
                this.loadExisitingMailTemplateList();
                this.clearForm();
              } else {
                this.SpinnerService.hide();
                this.toastr.error('Mail Template exists already');
              }
            }, error => {
              this.SpinnerService.hide();
              this.toastr.error(error);
            });
        }
      } else {
        this.toastr.error('Mail content should not be empty');
      }
    }
  }

  // method to clear the form
  clearForm() {
    this.submitted = false;
    this.action = 'add';
    this.mailTemplateForm.reset();
    this.richtext.setValue('');
    this.currentEmailTemplate = '';
    this.textBoxTouched = false;
  }

  // method to get the form data
  get formdata() { return this.mailTemplateForm.controls; }


  // click event for edit icon in the grid
  editMailTemplate(mailtemplateid, mailtemplatename, action) {
    if ((this.currentEmailTemplate !== '') && ((this.textBoxTouched === true) || (this.mailTemplateForm.touched === true))) {
      if (action !== 'view') {
        this.confirmation(mailtemplateid, mailtemplatename, action);
      }
    } else {
      if (action === 'view') {
        this.isViewMode = true;
      }
      this.mailTemplateForm.value.mailtemplateid = mailtemplateid;
      this.currentEmailTemplate = mailtemplatename;
      this.textBoxTouched = false;
      this.mailTemplateForm.value.mailtemplatename = null;
      if (this._mailTemplateListTmp.length > 0) {
        const resultData = this._mailTemplateListTmp.filter(e => e.mailtemplateid === mailtemplateid &&
          e.mailtemplatename === mailtemplatename);
        if (resultData.length > 0) {
          this.mailTemplateForm.controls['mailtemplatename'].setValue(resultData[0].mailtemplatename);
          this.richtext.setValue(resultData[0].body);
          this.mailTemplateForm.controls['subject'].setValue(resultData[0].subject);
          this.action = action;
          this.mailTemplateForm.controls['active'].setValue(resultData[0].active);
          this._mailTemplateId = resultData[0].mailtemplateid;
        }
      }
    }
  }

  // function for confirmation dialog before update the mail template
  confirmation(mailtemplateid, mailtemplatename, action) {
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Confirmation',
        message: 'Would you like to save changes? ' + this.currentEmailTemplate,
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.saveTemplate(action);
        } else {
          this.mailTemplateForm.markAsUntouched();
          this.textBoxTouched = false;
          this.currentEmailTemplate = '';
          this.editMailTemplate(mailtemplateid, mailtemplatename, action);
        }
      });

  }


  // function to activate or deactivate the mail template
  statusChange(id, option) {
    this.userid = +localStorage.getItem('userid');
    if (option === 'activate') {
      this.confmsg = 'activate';
      this.mailTemplateForm.value.active = 1;
      this.msg = 'Record activated successfully';
    } else {
      this.confmsg = 'deactivate';
      this.mailTemplateForm.value.active = 0;
      this.msg = 'Record deactivated successfully';
    }
    this.mailTemplateForm.value.mailtemplateid = id;
    this.mailTemplateForm.value.updatedby = this.userid;
    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.SpinnerService.show();
          this.mailtemplateService.Delete(this.mailTemplateForm.value).subscribe(
            (res) => {
              if (res.body !== 0) {
                this.toastr.success(this.msg);
                this.loadExisitingMailTemplateList();
              }
              this.SpinnerService.hide();
            }, error => {
              this.SpinnerService.hide();
              this.toastr.error(error);
            });
        }
      });
  }


  // auto focus fot txtfields in the form
  formFieldsAutoFocus() {
    this.myTxtMailTemplateName.nativeElement.focus();
  }

  // function to load mail field list
  loadMailFieldList() {
    this.SpinnerService.show();
    this._mailFieldService.Get().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this._mailFieldList = JSON.parse(res[0]);
        }
      }
      this.loadRichTextBox();
      this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting the mail fields data');
    });
  }

  // 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;
          }
        }
      });
    }
  }

}
