import { Component, OnInit, TemplateRef } from '@angular/core';
import { UserService } from './user.service';
import { User } from './user';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap/modal';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DepartmentService } from '../department/department.service';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import { DialogService } from 'ng2-bootstrap-modal';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  sendMenuId = 1;
  sendPageName = 'Add User';
  Users: User[] = [];
  UserList: User[] = [];
  UserListactive: any = [];

  p = 1; public searchText: string;
  itemsPerPage = 10;

  showall = true;
  
  showallstatus = false;
  actionRights: any; _menuId: any; readOnly: boolean; add: boolean; edit: boolean = true; delete: boolean = true; submitShow: boolean;
  useridnew: string = localStorage.getItem('userid');
  key = 'firstname';
  reverse = false;
  constructor(
    private userservice: UserService,
    private router: Router,
    private SpinnerService: NgxSpinnerService,
    private dialogService: DialogService,
    private toastr: ToastrService) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('User_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('User_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('User_userRights');
    }

  }


  ngOnInit() {
    this.SpinnerService.show();
    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;
          }
        }
      });
    }
  }

  getAll() {
    this.SpinnerService.show();
    this.UserList = [];
    this.UserListactive = [];
    this.userservice.Get().subscribe(res => {
console.log(JSON.parse(res[0]))
      this.Users = JSON.parse(res[0]);
      this.UserList = JSON.parse(res[0]);
      if (this.showallstatus === true) {
        this.UserList = this.UserList.filter(u => u.active === 1);
      }
      this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting users data');
    });

  }


  getactiveinactive(showallp) {
    this.SpinnerService.show();
    this.UserListactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.UserList.forEach(data => {
        if (data.active === 1) {
          this.UserListactive.push(data);
        }
      });
      this.UserList = [];
      this.UserList = this.UserListactive;
    } else {
      this.showall = true;
      this.UserList = [];
      this.getAll();
    }
    this.SpinnerService.hide();
  }

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

  calluseradd(userid: number) {
    this.SpinnerService.show();
    this.router.navigate(['/masters/useradd'], { queryParams: { userid: userid } });
  }


  OpenConfirmTemplate(user: User) {
    let confmsg;

    if (user.active === 0) {
      confmsg = 'activate';
    } else {
      confmsg = 'deactivate';
    }
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure you want to ' + confmsg + ' this record ?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.Delete(user);
        }

      });
  }


  Delete(user: User) {
    debugger;
    let msg;
    this.SpinnerService.show();
    if (user.active === 0) {
      user.active = 1;
      msg = 'User activated successfully';
    } else {
      user.active = 0;
      msg = 'User deactivated successfully';
    }
    user.menumapped = JSON.stringify(user.menumapped);
    user.accessrequestid = 1;
    this.userservice.Delete(user).subscribe(res => {
      this.toastr.success(msg);
      this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Operation is not successfull');
    });

  }


}
