import { EmployeeHttpService } from './../services/employee/employee-http.service';
import { Observable } from 'rxjs/Rx';
import { Component, OnInit, Output, EventEmitter, AfterViewInit } from '@angular/core';
import { LocalStorageService } from 'angular-2-local-storage';
import { AuthService } from '../services/auth.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { Router } from '@angular/router';
import { environment } from '../../environments/environment.dev';
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.scss']
})
export class EmployeeComponent implements OnInit, AfterViewInit {
  img_path_prefix = environment.imageUrl + '/assets/img/employee/post_login/';
  img_path_suffix = '_icon.png';

  @Output()
  closeNav = new EventEmitter();

  tiles_template = [
    {
      title: 'My Space', link: '/employee/dashboard', src: this.img_path_prefix + 'emp' + this.img_path_suffix,
      cols: 2, rows: 1, hidden: false
    },
    {
      title: 'TA', link: '/ta', src: this.img_path_prefix + 'ta' + this.img_path_suffix,
      cols: 1, rows: 1, hidden: false
    },
    {
      title: 'Candidate', link: '/introduction', src: this.img_path_prefix + 'emp' + this.img_path_suffix,
      cols: 2, rows: 1, hidden: false
    },
    {
      title: 'Coach', link: '/coach/landing', src: this.img_path_prefix + 'coach' + this.img_path_suffix,
      cols: 1, rows: 1, hidden: false
    },
    {
      title: 'PG Manager', link: '/PGlanding', src: this.img_path_prefix + 'pgm' + this.img_path_suffix,
      cols: 2, rows: 1, hidden: false
    },
    {
      title: 'Admin', link: '/admin', src: this.img_path_prefix + 'pgm' + this.img_path_suffix,
      cols: 3, rows: 1, hidden: false
    },
  ];

  tiles = [];

  userName = 'Andre Franklin';
  isError: boolean;
  error: string;
  employee: {
    accessToken: any,
    idpType: any,
    adId: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    locationName: any,
    roles: any,
    email: any,
    profileImgId: any,
    skills: any,
    location: any,
    firstTimeLogin: any
  };
  dialogData: any;
  roleNameEmployee;
  firstTimeLogin: boolean;

  roleToTileMap = {
    'EMPLOYEE': 0,
    'TA': 1,
    'CANDIDATE': 2,
    'COACH': 3,
    'HEAD_COACH': 4,
    'ADMIN': 5,
  };

  // API Mock JSON Response
  json =
    {
      infoMstr: {
        userInfoMstrId: 1,
        pgRoleUser: [
          {
            roleUserId: 1,
            pgRolePrivilege: {
              rolePrivilegeId: 4,
              pgRoleMstr: {
                roleId: 4,
                roleName: 'EMPLOYEE',
              }
            }
          },
          {
            roleUserId: 4,
            pgRolePrivilege: {
              rolePrivilegeId: 4,
              pgRoleMstr: {
                roleId: 2,
                roleName: 'COACH',
              }
            }
          },
          {
            roleUserId: 4,
            pgRolePrivilege: {
              rolePrivilegeId: 4,
              pgRoleMstr: {
                roleId: 3,
                roleName: 'TA',
              }
            }
          },
          {
            roleUserId: 1,
            pgRolePrivilege: {
              rolePrivilegeId: 4,
              pgRoleMstr: {
                roleId: 4,
                roleName: 'HEAD_COACH',
              }
            }
          },
          {
            roleUserId: 1,
            pgRolePrivilege: {
              rolePrivilegeId: 4,
              pgRoleMstr: {
                roleId: 4,
                roleName: 'ADMIN',
              }
            }
          }
        ]
      }
    };

  constructor(protected localStorageService: LocalStorageService,
    private router: Router,
    private AuthService: AuthService,
    private toastr: ToastsManager,
    private dataService: EmployeeHttpService,
  ) {
    let roles = [];
    const user: any = this.localStorageService.get('userInfo');

    this.localStorageService.remove('FilterItem');

    this.singleRole(roles);

    this.dataService
      .getEmployeeDetails(user['userInfoMstrId'])
      .subscribe(
        (data) => {
          let userDetails = data.pgUserInfoDtlsList[0];
          userDetails.firstTimeLogin = data.pgUserInfoDtlsList[0].firstTimeLogin;

          console.log(userDetails)

          if (userDetails.firstTimeLogin) {
            this.tiles_template[0].link = '/employee/first-time';
          }


          const roles = [];
          userDetails.pgUserInfoMstr.pgRoleUser.forEach(usrRole => {
            roles.push(usrRole.pgRolePrivilege.pgRoleMstr.roleName);
          });

          // to do null check for pgUserFileMapping
          let profileImg
          if (userDetails.pgUserInfoMstr.pgUserFileMapping) {
            profileImg = userDetails.pgUserInfoMstr.pgUserFileMapping.find(f => f.fileType === 'PROFILEIMAGE');
          }

          const json = {
            accessToken: user['accessToken'],
            idpType: user.idpType,
            adId: userDetails.adId,
            fullName: userDetails.pgUserInfoMstr.fullName,
            firstName: userDetails.pgUserInfoMstr.firstName,
            userInfoMstrId: userDetails.pgUserInfoMstr.userInfoMstrId,
            userInfoDtlsId: userDetails.userInfoDtlsId,
            profileImgId: profileImg ? profileImg.fileId : null,
            roles: roles,
            locationName: userDetails.pgUserInfoMstr.pgLocation.city,
            email: userDetails.pgUserInfoMstr.emailId,
            firstTimeLogin: userDetails.firstTimeLogin,
            status: userDetails.pgUserInfoMstr.status
          };
          console.log(json, 'userInfoDtlessss');
          // console.log(profileImg, 'profileImgValidation ');
          this.localStorageService.set('userInfo', json);
          this.employee = this.localStorageService.get('userInfo');

          console.log(this.employee, 'LocalStorage Datass')
          if (this.employee['fullName']) {
            this.userName = this.employee['fullName'];
            //roles = this.employee['roles'];
          }
          /* this.employee.adId = data.pgUserInfoDtlsList[0].adId; */
          //  this.localStorageService.set('userInfo', this.employee);

          // Rearrange tiles to show those that are valid first and to hide the rest
          this.tiles = Object.assign([], this.tiles_template);
          const rolesLength = roles.length;

          if (rolesLength !== 6) {
            const roleNames = Object.keys(roles);
            let tileIndex = 0;
            Object.keys(this.roleToTileMap).forEach((roleName, index) => {
              if (roles.indexOf(roleName) > -1) {
                if (index !== tileIndex) {
                  const tile = Object.assign({}, this.tiles_template[index]);
                  tile.cols = this.tiles[tileIndex].cols;
                  tile.rows = this.tiles[tileIndex].rows;
                  this.tiles[tileIndex] = tile;
                }
                tileIndex++;
              }
            });
            for (let i = tileIndex; i < this.tiles_template.length; i++) {
              this.tiles[i].hidden = true;
            }
          }
        });
  }

  ngOnInit() {
    this.dialogData = { title: 'Terminate Current Session', text: 'Do you really want to terminate the current session ?' }
  }

  ngAfterViewInit() {
    const user: any = this.localStorageService.get('userInfo');
    if (user.roles.length === 1 && user.roles[0] === 'EMPLOYEE') {
      this.roleNameEmployee = 'expand';
    } else {
      this.roleNameEmployee = '';
    }
  }

  checkRoles(e) {

    let role = ["EMPLOYEE", "ADMIN", "TA", "HEAD_COACH", "COACH"]
    //return new RegExp(e).test(this.employee.roles);
    return new RegExp(e).test(this.employee.roles);

  }


  closeNavDetails() {
    this.closeNav.emit(false);
  }

  routeAuth(role, path) {
    // document.getElementById("delConfModal").click();
    if (role) {
      this.localStorageService.set('selectedRole', role);
    }
    if (role === 'Coach' || role === 'PG Manager' || role === 'Employee') {
      this.AuthService.getUserDetails({ accessToken: this.employee['accessToken'], idpType: 'o365Identity' }).then(response => {
        if (response.status === 'success') {
          const userDetails = JSON.parse(response['data']);
          if (userDetails.infoMstr.pgUserSkillMapping.length === 0 || userDetails.infoMstr.pgLocation.length === 0) {
            this.toastr.warning('Please contact our Admin team.');
          } else {
            const skills = [];
            userDetails.infoMstr.pgUserSkillMapping.forEach(usrSkills => {
              skills.push(usrSkills.pgSkillTrackDtls.pgSkillTrackMstr.skillTrackMstrId);
            });
            const json = {
              accessToken: this.employee['accessToken'],
              adId: this.employee['adId'],
              loginType: this.employee['loginType'],
              fullName: this.employee['fullName'],
              firstName: this.employee['firstName'],
              userInfoMstrId: this.employee['userInfoMstrId'],
              roleName: this.employee['roleName'],
              locationName: this.employee['locationName'],
              roles: this.employee['roles'],
              email: this.employee['email'],
              profileImgId: this.employee['profileImgId'],
              skills: skills,
              location: userDetails.infoMstr.pgLocation.locationId
            };
            console.log(json, 'New JSON');
            this.localStorageService.clearAll();
            this.localStorageService.set('userInfo', json);
            this.localStorageService.set('selectedRole', role);
            if (role === 'PG Manager') {
              this.router.navigate(['pgm/landing']);
            } else {
              this.router.navigate([path]);
            }
          }
        } else {
          this.isError = true;
          this.error = 'Please contact our Tanlent Acquisition team.';
        }
      }).catch(err => {
        console.log(err);
      });

    } else {
      this.router.navigate([path]);
    }
  }




  singleRole(role) {
    if (role.length == 1 && role[0] == 'CANDIDATE') {
      this.router.navigate(['introduction']);
    }
  }


  selectSession(e) {

    console.log(e);
    if (e === 'TA') {

      if (new RegExp('HEAD_COACH').test(this.employee.roles)) {
        this.localStorageService.set('userSession', 'HEAD_COACH');

        this.router.navigate(['ta']);

      } else if (new RegExp('COACH').test(this.employee.roles)) {
        this.localStorageService.set('userSession', 'COACH');

        this.router.navigate(['ta']);

      } else if (new RegExp('TA').test(this.employee.roles)) {
        this.localStorageService.set('userSession', 'TA');

        this.router.navigate(['ta']);

      } else {

        //this.router.navigate(['ta']);

      }

    }
    if (e === 'AC') {
      if (new RegExp('ADMIN').test(this.employee.roles)) {
        this.router.navigate(['admin']);
      }
    }
    if (e === 'TT') {
      if (new RegExp('HEAD_COACH').test(this.employee.roles)) {
        this.router.navigate(['talent-transformation/landing/employee']);
      }
    }
    if (e === 'MS') {
      if (new RegExp('EMPLOYEE').test(this.employee.roles)) {
        this.router.navigate(['employee/dashboard']);
      }
    }
    if (e === 'EE') {
      if (new RegExp('EMPLOYEE').test(this.employee.roles)) {
        this.router.navigate(['employee/engEnv']);
      }
    }

  }

}
