import { Component, OnInit, ElementRef, ViewChild  } from '@angular/core';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { FormGroup, FormBuilder, Validators, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import { DialogService } from 'ng2-bootstrap-modal';
import { MenurightsComponent } from '../../Shared/menurights/menurights.component';
import * as $ from 'jquery'; declare let $: any;
import { Role } from './role';
import { RoleService } from './role.service';
import { UserService } from '../user/user.service';
import { NgxSpinnerService } from 'ngx-spinner';


@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.css']
})
export class RoleComponent implements OnInit {
  @ViewChild('txtRoleName', { static: false }) myTxtRoleName: ElementRef;
  roleForm: FormGroup;
  roles: Role[];
  role: Role;
  submitted = false;

  _action: string;
  _roleList: any = [];
  _roleListactive: any = [];
  showallstatus = false;
  showall = true;
  textBoxTouched: boolean;
  currentRole: string;
  _roleId: any;

  // local storage variables
  userid: number;

  // sorting variables
  key = 'Role Name';
  reverse = false;

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

  // menurights variables
  checkedstatus: boolean;
  actionArray = [];

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

  // grid search variables
  searchText: string;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  constructor(
    private router: Router,
    private toastr: ToastrService,
    private roleService: RoleService,
    private formBuilder: FormBuilder,
    private dialogService: DialogService,
    private _menuRights: MenurightsComponent,
    private userService: UserService,
    private SpinnerService: NgxSpinnerService) {
      // get rights for the logged in user for the particular component
     if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Role_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Role_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
  } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Role_userRights');
  }
     }

  ngOnInit() {
    this.roleForm = this.formBuilder.group({
      roleid: [''],
      rolename: ['', [Validators.required]],
      description: ['', [Validators.required]],
      menumapped: ['']
    });
    this._action = 'add';
    this.textBoxTouched = false;
    this.currentRole = '';
    this._roleId = '';
    this.loadExisitingRoleList();
    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;
        }
      }
    });
  }
}
  // function to sort the columns values
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }

  // function to get the existing role details
  loadExisitingRoleList() {
    this.SpinnerService.show();
    this._roleList = [];
    this._roleListactive = [];
    this.roleService.Get().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this._roleList = JSON.parse(res[0]);
          if (this.showallstatus === true) {
            this._roleList.forEach(data => {
              if (data.active === 1) {
                this._roleListactive.push(data);
              }
            });
            this._roleList = [];
            this._roleList = this._roleListactive;
          }
        }
      }
      this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting data'); });
  }
  get formdata() { return this.roleForm.controls; }
  // Save and update method
  async postRole(role: Role) {
    this.submitted = true;
    if (this.roleForm.valid) {
      this.checkedstatus = this._menuRights.getselectedmenuscheck();
      if (this.checkedstatus === false) {
        this.toastr.error('Atleast one menus with required rights should get selected');
        return;
      }
      this.actionArray = this._menuRights.getselectedmenus();
      role.menumapped = JSON.stringify(this.actionArray);
      role.roleid = 0;
      this.userid = +localStorage.getItem('userid');
      if (this._action === 'add') {
        this.SpinnerService.show();
        role.createdby = this.userid;
        role.active = 1;
        this.roleService.Post(role).subscribe((res) => {
          if (res.body !== 0) {
            this.toastr.success('Data added successfully');
            this.SpinnerService.hide();
            this.clearForm();
            this.loadExisitingRoleList();
          } else {
            this.SpinnerService.hide();
            this.toastr.error('Role exists already');
          }
        },
          error => {
            this.SpinnerService.hide();
          });
      }
      // updating the role information
      if (this._action === 'update') {
        role.updatedby = this.userid;
        role.roleid = this._roleId;
        // check if user mapped in this role
        let isRoleMapped: any;
        isRoleMapped = await this.checkRoleMappedWithUser(this._roleId);
        if (isRoleMapped !== undefined && isRoleMapped != null && isRoleMapped[0] !== undefined && isRoleMapped[0] !== null &&
          (JSON.parse(isRoleMapped[0]).length > 0 )) {
          this.dialogService.addDialog(CommondialogComponent,
            {
              title: 'Confirmation',
              message: 'Would you like to proceed the same changes for mapped users? ',
              hclass: 'modelsuccess',
              oktext: 'Yes',
              canceltext: 'No',
              okshow: true,
              cancelshow: true
            }).subscribe((isConfirmed) => {
              if (isConfirmed) {
                this.roleUpdate(role);
              }
            });
        } else {
          this.roleUpdate(role);
        }
      }
    }
    this.submitted = false;
  }

  chkArrayTouched() {
    this.textBoxTouched = true;
  }
  // cancel button and control refresh method
  clearForm() {
    this.submitted = false;
    this._action = 'add';
    this.actionArray = [];
    this.roleForm.reset();
    this.textBoxTouched = false;
    this.currentRole = '';
    this._menuRights.reset();
   // this.formFieldsAutoFocus();
  }
  // click event for edit icon in the grid
  editRole(roleid, rolename, action) {
    if ((this.currentRole !== '') && ((this.roleForm.touched === true) || (this.textBoxTouched === true))) {
      this.confirmation(roleid, rolename, action);
    } else {
      this._menuRights.reset();
      this.currentRole = rolename;
      this.roleForm.value.roleid = roleid;
      this.roleForm.value.rolename = null;
      if (this._roleList.length > 0) {
        const resultData = this._roleList.filter(e => e.roleid === roleid && e.rolename === rolename);
        if (resultData.length > 0) {
          this.roleForm.controls['rolename'].setValue(resultData[0].rolename);
          this.roleForm.controls['description'].setValue(resultData[0].description);
          this._menuRights.roleChange(resultData[0].menumapped);
          this._action = action;
          this._roleId = resultData[0].roleid;
        }
      }
    }
  }

  confirmation(roleid, rolename, action) {
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Confirmation',
        message: 'Would you like to save changes? ' + this.currentRole,
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.postRole(this.roleForm.value);
        } else {
          this.currentRole = '';
          this.roleForm.markAsUntouched();
          this.textBoxTouched = false;
          this._menuRights.reset();
          this.editRole(roleid, rolename, action);
        }
      });
  }

  // function to activate or deactivate the team
  statusChange(id, option) {
    this.userid = +localStorage.getItem('userid');
    if (option === 'activate') {
      this.confmsg = 'activate';
      this.roleForm.value.active = 1;
      this.msg = 'Record activated successfully';
    } else {
      this.confmsg = 'deactivate';
      this.roleForm.value.active = 0;
      this.msg = 'Record deactivated successfully';
    }
    this.roleForm.value.roleid = id;
    this.roleForm.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(async (isConfirmed) => {
        if (isConfirmed) {
          // check if user mapped in this role
          let _isRoleMapped: any;
          _isRoleMapped = await this.checkRoleMappedWithUser(id);
          if (_isRoleMapped !== undefined && _isRoleMapped != null && _isRoleMapped[0] !== undefined && _isRoleMapped[0] === null ) {
            this.SpinnerService.show();
            this.roleService.Delete(this.roleForm.value).subscribe(
              (res) => {
                if (res.body !== 0) {
                  this.SpinnerService.hide();
                  this.toastr.success(this.msg);
                  this.loadExisitingRoleList();
                }
              }, error => {
                this.SpinnerService.hide();
                this.toastr.error(error);
              });
          } else {
            this.toastr.warning('The role is assigned to the user');
          }
        }
      });
  }

  // get show all active function
  getactiveinactive(showallp) {
    this._roleListactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this._roleList.forEach(data => {
        if (data.active === 1) {
          this._roleListactive.push(data);
        }
      });
      this._roleList = [];
      this._roleList = this._roleListactive;
    } else {
      this.showall = true;
      this._roleList = [];
      this.loadExisitingRoleList();
    }
  }

  async checkRoleMappedWithUser(roleId) {
    const inputData = [];
    inputData.push({
      roleid: roleId
    });
    return await this.userService.GetByRoleId(inputData[0]).toPromise().then(res => res.body);
  }

  // funstion to update the role information
  roleUpdate(role) {
    this.SpinnerService.show();
    this.roleService.Put(role).subscribe(
      (res) => {
        if (res.body !== 0) {
          this.toastr.success('Data updated for role successfully');
          this.SpinnerService.hide();
          this.loadExisitingRoleList();
          this.clearForm();
        } else { this.SpinnerService.hide(); this.toastr.error('Role exists already'); }
      }, error => {
        this.SpinnerService.hide();
        this.toastr.error(error);
      });
  }

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

}
