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 { Stagetype } from './stagetype';
import { StagetypeService } from './stagetype.service';

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

    sendMenuId: number;
    sendPageName = 'Stagetype';
    _menuId: any;
    actionRights: any;
    readOnly = false; add = false; edit = false; delete = false;
    stagetypeForm: FormGroup;
    stagetypes: Stagetype[] = [];
    stagetypesactive: Stagetype[] = [];
    stagetype: Stagetype;
    deleteResult: boolean;
    postresult: boolean;
    putDResult: boolean;
    stagetypeModalRef: BsModalRef;
    operation: string;
    userid: number;
    stagetypeid: 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 = 'stagetype';
    reverse = false;

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

    ngOnInit() {
        this.stagetypeForm = this.formBuilder.group({
            stagetypeid: [''],
            stagetype: ['', [Validators.required]],
            isserver: [''],
            active: ['']
        });
        this.searchText = '';
        this.getAll();
this.getUserRights();

    }
 // 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.stagetypesactive = [];
        this.showall = showallp;
        this.showallstatus = showallp;
        if (this.showall === true) {
            this.showall = false;
            this.stagetypes.forEach(data => {
                if (data.active === 1) {
                    this.stagetypesactive.push(data);
                }
            });
            this.stagetypes = [];
            this.stagetypes = this.stagetypesactive;
        } else {
            this.showall = true;
            this.stagetypes = [];
            this.getAll();
        }
    }

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

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


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

    }

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

    Post(stagetype: Stagetype) {
        this.submitted = true;

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

        let msg = null;

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

            stagetype.createdby = this.userid;
            msg = 'Record Added Successfully';
            this.stagetypeservice.Post(stagetype).subscribe(res => {
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.stagetypeModalRef.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') {
            stagetype.updatedby = this.userid;
            msg = 'Record updated successfully';
            this.stagetypeservice.Put(stagetype).subscribe(res => {
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.stagetypeModalRef.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;
    }

   

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

                    this.Delete();

                }

            });

    }

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

    }

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

    openStagetypeModal(template: TemplateRef<any>, type, stagetype?: Stagetype) {

        this.operation = type;

        if (type === 'update') {
            this.stagetypeForm.controls['stagetypeid'].setValue(stagetype.stagetypeid);
            this.stagetypeForm.controls['stagetype'].setValue(stagetype.stagetype);
            this.stagetypeForm.controls['active'].setValue(stagetype.active);
            this.stagetypeForm.controls['isserver'].setValue(stagetype.isserver);
            this.stagetype = stagetype;
        }
        if (type === 'add') {
            this.stagetypeForm.controls['stagetypeid'].setValue(0);
            this.stagetypeForm.controls['stagetype'].setValue('');
            this.stagetypeForm.controls['active'].setValue(1);
            this.stagetypeForm.controls['isserver'].setValue(1);
        }
        this.stagetypeModalRef = this.modalService.show(template, this.config);

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

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