import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { AuthService } from '../../../../../services/auth.service';
import { FormBuilder, FormGroup, Validators, AbstractControl, FormArray, FormControl } from '@angular/forms';
import _ from "lodash";
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

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

@Component({
  selector: 'app-user-form',
  templateUrl: './user-form.component.html',
  styleUrls: ['./user-form.component.scss']
})
export class UserFormComponent implements OnInit {

  isEdit:boolean;
  userFormTitle: string;
  locations = [];
  roles: any;
  roleKeys = [];
  roleList = [];
  rolePrivilege = false;
  privileges: any;
  skilltrackResponse: any;
  Skills: any;
  editUserDisabled: boolean = false;
  selectedSkillValues: any;
  errMsg = '';
  skillArrUsr : any = [];
  newusrFormdet: any;
  rolesList: any;
  private selectedChecked=[];
  
  @Input() userDtEdit: any;
  @Output() closeUsrMgmtForm = new EventEmitter();

  constructor(private AuthService: AuthService, private toastr: ToastsManager) {
    // this.getAllUser();
    this.getAllSkills();
    this.getAllLocation();
    this.getAllRoleAndPrivileges();
   }

  ngOnInit() {
    
    this.userFormTitle = "Add User"
    this.newusrFormdet = {};
   
    if(this.userDtEdit){
      this.userFormTitle = "Edit User"
     console.log(JSON.stringify(this.userDtEdit));
      this.newusrFormdet.firstName = this.userDtEdit.pgUserInfoMstr.firstName;
      this.newusrFormdet.lastName = this.userDtEdit.pgUserInfoMstr.lastName;
      this.newusrFormdet.email = this.userDtEdit.pgUserInfoMstr.emailId;
      this.newusrFormdet.location = this.userDtEdit.pgUserInfoMstr.pgLocation.locationId;
      this.editUserDisabled = true;
      this.isEdit = true;
      if(this.userDtEdit.pgUserInfoMstr.pgRoleUser && this.userDtEdit.pgUserInfoMstr.pgRoleUser.length != 0){
        this.newusrFormdet.role = [];
        // this.userDtEdit.pgUserInfoMstr.pgRoleUser.forEach(element => {
        //   this.newusrFormdet.role.push(element.pgRolePrivilege.pgRoleMstr.roleId);
        // });
        this.userDtEdit.pgUserInfoMstr.pgRoleUser.forEach(element => {
          this.newusrFormdet.role.push(element.pgRolePrivilege.pgRoleMstr.roleId);
        });
        console.log("role array items",this.newusrFormdet.role)
      }
      this.newusrFormdet.userInfoMstrId = this.userDtEdit.pgUserInfoMstr.userInfoMstrId;
      this.newusrFormdet.userInfoDtlsId = this.userDtEdit.userInfoDtlsId;
      // if(this.userDtEdit.pgUserSkillMapping && this.userDtEdit.pgUserSkillMapping.length != 0){
      //   this.newusrFormdet.skillTrackMstrId = this.userDtEdit.pgSkillTrackMstr.skillTrackMstrId;
      //   this.selectedSkillValues = this.newusrFormdet.skillTrackMstrId;
      //   this.newusrFormdet.skillTrackName = this.userDtEdit.pgSkillTrackMstr.skillTrackName;
        
      //   this.newusrFormdet.skillTrackName = this.userDtEdit.pgUserSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackName;
      //   this.newusrFormdet.skillTrackMstrId = this.userDtEdit.pgUserSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackMstrId;
      //   this.onSkillMaster(null, this.newusrFormdet.skillTrackMstrId);
      //   this.skillArrUsr = this.userDtEdit['pgUserSkillMapping'].map((skillMap)=>skillMap['pgSkillTrackDtls']['skillTrackDtlsId'])
      // }
    }
  }

  getAllSkills(){

    this.AuthService.getAllSkill().then(resp =>{
     // console.log(resp,'getAllSkill')
      this.Skills = resp.pgSkillTrackDtlsList
      var customSkill = []
      var skills = _.uniqBy(resp.pgSkillTrackDtlsList,'pgSkillTrackMstr.skillTrackName')
      var masterSkills = _.uniqBy(_.flattenDeep(skills.map(i => i.pgSkillTrackMstr)))
      masterSkills.forEach(usrSkills => {
        var dtlsSkill = resp.pgSkillTrackDtlsList.filter(item => item.pgSkillTrackMstr.skillTrackName == usrSkills.skillTrackName)
        var skillTrackDtlsName = _.uniqBy(_.flattenDeep(dtlsSkill.filter(i => {return {id : i.skillTrackDtlsId, name : i.skillTrackDtlsName}})))
        customSkill.push({skillMaster:usrSkills,skillTrackDtls :dtlsSkill,skillTrackDtlsName:skillTrackDtlsName});
      });
    //  console.log(customSkill);
      this.skilltrackResponse = customSkill;
    }).catch(err =>{

      console.log(err)
    })
  }
  
  getAllLocation(){
    this.AuthService.getAllLocations().then(resp =>{
      console.log(resp,'getAllLocations')
      this.locations = resp.pgLocationList
    }).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.rolesList = resp.roleList
      // }).catch(err =>{
      //   console.log(err)
      // })
      this.AuthService.getAllRolePrivilege().then(resp =>{
        console.log(resp,'getAllRolePrivilege')
        this.rolesList = resp.pgRolePrivileges
      }).catch(err =>{
        console.log(err)
      })
  }

  onSkillMaster(e, data){
    // console.log(e);
    // console.log("data -- "+JSON.stringify(data));
    this.selectedSkillValues = data;
    console.log(this.selectedSkillValues);
  }

  updateCheckedOptions(id, status){
    // console.log("checkbox selected --- ", status.target.value, id, status);
    if(status.target.checked === true ){
    this.skillArrUsr.push(id);
    }
    else{
      this.skillArrUsr.splice(this.skillArrUsr.indexOf(id), 1)
    }
    this.newusrFormdet.skillArrUsr = this.skillArrUsr;
    console.log(this.newusrFormdet.skillArrUsr );
  }

  changeEvent(e, item) {
    console.log(item);
    this.selectedChecked[item] = e.checked;
    
    if(e.checked == true){
     this.roles[item].checked=true;   
   //  this.acs.Check=this.selectedChecked;
    
    }
    else{
   //   this.acs.Check=this.selectedChecked;
    }
  }

  createUserfromAdmin(newusrFormdet){
    let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    //console.log('you submitted value: ' ,newusrFormdet);
    this.errMsg = ''
     if (newusrFormdet.email == null || newusrFormdet.email == "" || newusrFormdet.email == undefined || !re.test(newusrFormdet.email)) {
      this.errMsg = "Please provide a valid email.";
    }
    else if ((this.newusrFormdet.role == null || undefined) || (this.newusrFormdet.role.length < 0 )){
      this.errMsg = "Please select atleast one Role";
    }
    else {
      console.log("Add User API")
          this.AuthService.getaddNewUser(newusrFormdet).then(resp => {
            //console.log(resp, 'response')
            if (resp.error !== null) {
              this.toastr.error(resp.error);
            }
            
            else {
                this.toastr.success('User added successfully');
                this.newusrFormdet = {};
                this.cancelUserMForm();
            }
          }).catch(err => {
            console.log(err, "Error")
            this.toastr.error(err);
          })
    }
  }

  updateUserfromAdmin(newusrFormdet){
    this.errMsg = '';
    if ((this.newusrFormdet.role == null || undefined) || (this.newusrFormdet.role.length < 0 )){
      this.errMsg = "Please select atleast one Role";
    }
    else {
      // console.log("Edit User API -- ", JSON.stringify(this.newusrFormdet));
      this.AuthService.getEditUser(newusrFormdet).then(resp => {
        //console.log(resp, 'response')
        if (resp.error != null && resp.status != 200) {
          this.toastr.error(resp.error);
        }
        else {
            this.toastr.success('User Updated successfully');
            this.newusrFormdet = {};
            this.isEdit = false;
            this.userDtEdit = {}
            this.cancelUserMForm();                
        }
      }).catch(err => {
        console.log(err, "Error")
        this.toastr.error(err);
      })
    }
  }


  cancelUserMForm(){
    this.newusrFormdet = {};
    this.closeUsrMgmtForm.emit('true');
  }

}
