import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthService } from '../../../../services/auth.service';
import { FormBuilder, FormGroup, Validators, AbstractControl, FormArray, FormControl } from '@angular/forms';
import { NavBarService } from '../../../admin.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import * as _ from 'underscore';
import { PagerService } from './_services/index';
import { environment } from '../../../../../environments/environment.dev';

const privilegesSample = [
  { rolePrivilegeId: 0, accessType: 'View Only' },
  { rolePrivilegeId: 1, accessType: 'Add' },
  { rolePrivilegeId: 4, accessType: 'Edit' },
  { rolePrivilegeId: 3, accessType: 'Delete' }
];

@Component({
  moduleId: module.id,
  selector: 'app-user-mgmt',
  templateUrl: './user-mgmt.component.html',
  styleUrls: ['./user-mgmt.component.scss']
})
export class UserMgmtComponent implements OnInit {
  id: number;
  private sub: any;
  user = { firstName: '', lastName: '', email: '', employeeId: '', pref: 'Option 1'};

  name: string;
  prefs = [
   {name: 'Option 1'},
   {name: 'Option 2'}
  ];

  privileges: any;

  userForm: FormGroup;
  userFormFields: any;
  fetchingData: boolean = false;

  objectProps;

  usr_img_path = environment.imageUrl+'/assets/img/admin/';
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  selectedFilter = 2;

  // users = [
  //   { firstName: 'Roger', lastName: 'Harrinson', email: 'abcd@gmail.com', employeeId: '0', pref: 'Option 1'},
  //   { firstName: 'Roger', lastName: 'Harrinson', email: 'abcd@gmail.com', employeeId: '0', pref: 'Option 2'}
  // ];

  filters = [
    { name: 'Location', pWidth: 'auto' },
    { name: 'Role', pWidth: '40px' },
    { name: 'All', pWidth: '30px' }
  ];
  roles: any;
  roleKeys = [];
  locations = []
  Skills = []
  //usersLists = []
  roleList = []
  editBtn = false
  editStatus = false
  rolePrivilege = false
  errMsg = ''
  rolesAndPrivileges: FormArray;
  userList: boolean = true;
  addNewUserDet: boolean = true;
  // array of all items to be paged
  private usersLists: any[];
  private usersListsCopy: any[];

  // pager object
  pager: any = {};
  // paged items
  pagedItems: any[];
  userDtEdit:any;

  constructor(private router: Router,
    private route: ActivatedRoute,
    private AuthService: AuthService,
    private toastr: ToastsManager, private pagerService: PagerService) {
      this.getAllUser();
      // this.getAllSkills();
      // this.getAllLocation();
      // this.getAllRoleAndPrivileges();

    }

  ngOnInit() {
    // console.log(this.pager);
  }

  getAllUser(){
    this.fetchingData = true;
    this.AuthService.getAllUsers().then(resp =>{
     // console.log(resp,'getAllUsers');
      this.usersLists = resp.userList;
      this.usersListsCopy = resp.userList;
      this.fetchingData = false;
      this.setPage(1);
    }).catch(err =>{
      console.log(err)
    })
  }

  getAllPrivilege(role, roleIndex) {

    console.log(role)
    this.rolePrivilege = false

    if(role != 'Select') {

      this.AuthService.getAllPrivilege(role).then(resp => {

        console.log(resp, 'getAllPrivilege');

         this.privileges = resp.rolePrivList;
        console.log('Role ', role, ' Privileges ', this.privileges);

      }).catch(err => {

      })
    }

  }

  getAllRoleAndPrivileges() {

    // TODO: It is needed and endpoint that returns a roles list with the appropriate privileges list
    this.roles = {
      1: { roleName: 'CANDIDATE', privileges: privilegesSample  },
      2: { roleName: 'COACH', privileges: privilegesSample },
      3: { roleName: 'HEAD_COACH', privileges: privilegesSample },
      4: { roleName: 'EMPLOYEE', privileges: privilegesSample },
      5: { roleName: 'TA', privileges: privilegesSample },
      6: { roleName: 'ADMIN', privileges: privilegesSample }
    };

    this.roleKeys = Object.keys(this.roles);
    console.log('rolekeys ', this.roleKeys);

       this.AuthService.getAllRoles().then(resp =>{

        console.log(resp,'getAllRoles')

       // this.roles = resp.roleList


      }).catch(err =>{

        console.log(err)
      })

  }

  getAllLocation(){
    this.AuthService.getAllLocations().then(resp =>{
    console.log(resp,'getAllLocations')
    this.locations = resp.pgLocationList
    }).catch(err =>{
      console.log(err)
    })
  }

  getAllSkills(){
    this.AuthService.getAllSkill().then(res => {
      var skill = res;
      console.log(skill,"Skills")
      this.Skills = skill.pgSkillTrackDtlsList

      console.log(this.Skills,"Skills")
    }).catch(err=>{
      console.log(err)
    });
  }

  setPage(page: number) {
    if(this.pager.totalPages){
      if (page < 1 || page > this.pager.totalPages) {
          return;
      } 
    }
    // commented as we are facing issue during search !!!
    // get pager object from service
    this.pager = this.pagerService.getPager(this.usersLists.length, page);
    // console.log("Pager --- "+JSON.stringify(this.pager));
    // get current page of items
    this.pagedItems = this.usersLists.slice(this.pager.startIndex, this.pager.endIndex + 1);
  }

  addNewUserForm(){
    this.userList = false;
    this.addNewUserDet = true;
  }

  userFormCancel(){
    this.userList = true;
    this.getAllUser();
  }
  edituserDetails(e){
   // console.log('Editing User:', JSON.stringify(e));
    // this.editBtn = true;
    this.userList = false;
    this.addNewUserDet = false;
   this.userDtEdit = e;
  }

  SearchforUsers(e, data){
    if(data != null){
    let x = [];
    this.usersListsCopy.filter(obj => {
      if(obj.fullName){
        if (obj.fullName.toLowerCase().includes(data.toLowerCase())) {
          x.push(obj)
        }
      }
    })
    this.usersLists = x;
    this.setPage(1);
    // this.pagedItems = this.usersLists.slice(this.pager.startIndex, this.pager.endIndex + 1);
    }
    else{
      this.usersLists = this.usersListsCopy;
    }
  }
}
