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 { Projectdefinitionmaster } from './projectdefinitionmaster';
import { ProjectdefinitionmasterService } from './projectdefinitionmaster.service';


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

    sendMenuId: number;
    sendPageName = 'ProjectDefinition';
    _menuId: any;
    actionRights: any;
    submitShow: boolean;
    readOnly = false; add = false; edit = false; delete = false;
    projectdefinitionForm: FormGroup;
    projectdefinitions: any;
    projectdefinitionsactive: Projectdefinitionmaster[] = [];
    _projectDefinitionMaster: Projectdefinitionmaster;
    unit: Projectdefinitionmaster;
    deleteResult: boolean;
    postresult: boolean;
    putDResult: boolean;
    unitModalRef: BsModalRef;
    operation: string;
    userid: number;
    unitid: 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;
    reverse = false;
    projectDefinitionId: number;
    key = 'project_subtitle';
    constructor(
        private router: Router, private toastr: ToastrService,
         private dialogService: DialogService,
        private formBuilder: FormBuilder, private modalService: BsModalService,
        private projectdefinitionservice: ProjectdefinitionmasterService
        ) {
        // get rights for the logged in user for the particular component
        if (this.router.getCurrentNavigation().extras.state !== undefined) {
            localStorage.setItem('ProjectDefinitionMaster_menuid', this.router.getCurrentNavigation().extras.state.menuid);
            localStorage.setItem('ProjectDefinitionMaster_userRights', this.router.getCurrentNavigation().extras.state.action);
            this.actionRights = [];
            this.actionRights = this.router.getCurrentNavigation().extras.state.action;
        } else {
            this.actionRights = [];
            this.actionRights = localStorage.getItem('ProjectDefinitionMaster_userRights');
        }
    }

    ngOnInit() {
        this.projectdefinitionForm = this.formBuilder.group({
            projectdefinitionid: [''],
            project_subtitle: [''],
            projectid: [''],
            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.projectdefinitionsactive = [];
        this.showall = showallp;
        this.showallstatus = showallp;
        if (this.showall === true) {
            this.showall = false;
            this.projectdefinitions.forEach(data => {
                if (data.active === 1) {
                    this.projectdefinitionsactive.push(data);
                }
            });
            this.projectdefinitions = [];
            this.projectdefinitions = this.projectdefinitionsactive;
        } else {
            this.showall = true;
            this.projectdefinitions = [];
            this.getAll();
        }
    }

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

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


    getAll() {
        const input = [];
        this.userid = +localStorage.getItem('userid');
        input.push({ userid: this.userid });
        this.projectdefinitions = [];
        let projectDefinitionsTmp = [];
        this.projectdefinitionservice.getAllByUserId(input[0]).subscribe(res => {
            if (res.body[0] !== null && res.body[0] !== undefined) {
                projectDefinitionsTmp = JSON.parse(res.body[0]);
                this.projectdefinitions = projectDefinitionsTmp.map(k => ({
                    projectdefinitionid: k.projectdefinitionid,
                    project_subtitle: k.project_subtitle,
                    projectname: k.projectname,
                    createdbyname: k.createdbyname,
                    updatedbyname: k.updatedbyname,
                    createdon: k.createdon,
                    updatedon: k.updatedon,
                    active: k.active
                }));
                if (this.showallstatus === true) {
                    this.projectdefinitions = this.projectdefinitions.filter(y => y.active === 1);
                }
            }
        }, error => { this.toastr.error('Error while getting data'); });
    }


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

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

    OpenConfirmTemplate(item) {
        if (item.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.Delete(item);
                }

            });

    }

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

    }

    // method to navigate project definition page in edit mode/add
    moveProjectDefinition(item) {
        let projectDefinitionId = 0;
         if (item === 0) {
            projectDefinitionId = 0;
        } else {
            projectDefinitionId = item.projectdefinitionid;
        }
        const queryParams = {};
        const navigationExtras: NavigationExtras = {
          queryParams, state: {
            projectdefinitionid: projectDefinitionId
           }} ;
           this.router.navigate(['/projectconfiguration/projectdefinition'], navigationExtras);
      }

}
