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

@Component({
  selector: 'app-workflow',
  templateUrl: './workflow.component.html',
  styleUrls: ['./workflow.component.css']
})
export class WorkFlowComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'WorkFlow';
  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly: boolean; add: boolean; edit: boolean; delete: boolean;
  workflowForm: FormGroup;
  workflows: WorkFlow[] = [];
  workflowsactive: WorkFlow[] = [];
  workflow: WorkFlow;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  workflowModalRef: BsModalRef;
  operation: string;
  userid: number;
  workflowid: 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 = 'workflow'; // set default
  reverse = false;

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

  }

  ngOnInit() {
    this.workflowForm = this.formBuilder.group({
      workflowid: [''],
      workflowname: ['', [Validators.required]],
      description: ['', [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();
  }

  getactiveinactive(showallp) {
    this.workflowsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.workflows.forEach(data => {
        if (data.active === 1) {
          this.workflowsactive.push(data);
        }
      });
      this.workflows = [];
      this.workflows = this.workflowsactive;
    } else {
      this.showall = true;
      this.workflows = [];
      this.getAll();
    }
  }

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

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


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

  }

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

  Post(workflow: WorkFlow) {

    this.submitted = true;

    if ((workflow.workflowname.trim() === undefined) || (workflow.workflowname.trim() === '')) {
      this.toastr.error('WorkFlow should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    workflow.workflowname = workflow.workflowname.trim();
    if (this.operation === 'add') {
      workflow.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.workflowservice.Post(workflow).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.workflowModalRef.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;
      workflow.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.workflowservice.Put(workflow).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.workflowModalRef.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;
        });
    }
  }

  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.workflowForm.controls['active'].setValue(1);
    } else {
      this.workflowForm.controls['active'].setValue(0);
    }
  }

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

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

  hidePopup() {
    this.workflowModalRef.hide();
  }
  moveToWorkflowDefinition(item) {
    console.log(item);
    const queryParams = {};
    const navigationExtras: NavigationExtras = {
      queryParams, state: {
        workflowid: item.workflowid,
        workflowname: item.workflowname,
        description: item.description
       }} ;
        this.router.navigate(['/workflowconfiguration/workflowdefinition'], navigationExtras);
  }
  openWorkFlowModal(template: TemplateRef<any>, type, workflow?: WorkFlow) {
    this.operation = type;
    if (type === 'update') {
      this.workflowForm.controls['workflowid'].setValue(workflow.workflowid);
      this.workflowForm.controls['workflowname'].setValue(workflow.workflowname);
      this.workflowForm.controls['description'].setValue(workflow.description);
      this.workflowForm.controls['active'].setValue(workflow.active);
      this.workflow = workflow;
    }
    if (type === 'add') {
      this.workflowForm.reset();
      this.workflowForm.controls['workflowid'].setValue(0);
      this.workflowForm.controls['active'].setValue(1);
    }
    this.workflowModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
}
