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 { Stage } from './stage';
import { StageService } from './stage.service';

@Component({
  selector: 'app-stage',
  templateUrl: './stage.component.html',
  styleUrls: ['./stage.component.css']
})
export class StageComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Stage';
  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly: boolean; add: boolean; edit: boolean; delete: boolean;
  stageForm: FormGroup;
  stages: Stage[] = [];
  stagesactive: Stage[] = [];
  stage: Stage;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  stageModalRef: BsModalRef;
  operation: string;
  userid: number;
  stageid: 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 = 'stage';
  reverse = false;

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

  }

  ngOnInit() {
    this.stageForm = this.formBuilder.group({
      stageid: [''],
      stage: ['', [Validators.required]],
      stagedescription:[''],
      benchmark:[],
      active: ['']
    });
    this.searchText = '';
    this.getAll();
    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.stagesactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.stages.forEach(data => {
        if (data.active === 1) {
          this.stagesactive.push(data);
        }
      });
      this.stages = [];
      this.stages = this.stagesactive;
    } else {
      this.showall = true;
      this.stages = [];
      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.stageModalRef.hide();
  }

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


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

  }

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

  Post(stage: Stage) {

    this.submitted = true;

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

    let msg = null;
    if (!+stage.benchmark){
    stage.benchmark = 0;
  }
    this.userid = +localStorage.getItem('userid');
    stage.stage = stage.stage.trim();
    if (this.operation === 'add') {

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

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

          this.Delete();

        }

      });

  }

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

  }

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

  openStageModal(template: TemplateRef<any>, type, stage?: Stage) {

    this.operation = type;

    if (type === 'update') {
      this.stageForm.controls['stageid'].setValue(stage.stageid);
      this.stageForm.controls['stage'].setValue(stage.stage);
      this.stageForm.controls['active'].setValue(stage.active);
      this.stage = stage;
    }
    if (type === 'add') {
      this.stageForm.controls['stageid'].setValue(0);
      this.stageForm.controls['stage'].setValue('');
      this.stageForm.controls['active'].setValue(1);
		this.stageForm.controls['stagedescription'].setValue('');
      this.stageForm.controls['benchmark'].setValue('');													   
    }
    this.stageModalRef = this.modalService.show(template, this.config);

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

  }

}
