import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { Router } from '@angular/router';
import { LocalStorageService } from 'angular-2-local-storage';
import { NavBarService } from './ta.service';
import { MODAL_CONTENT, TaModalServiceService } from 'app/ta/ta-modal-service.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { AuthService } from 'app/services/auth.service';
import { SlideMenuModule } from 'cuppa-ng2-slidemenu/cuppa-ng2-slidemenu';
import { DomSanitizer } from '@angular/platform-browser';
import { environment } from '../../environments/environment.dev';
const taPages = [
  { title: 'List of Profiles', back: 'menu' },
  { title: 'Candidate Details', back: 'arrow_back' },
  { title: 'Add Candidate', back: 'arrow_back' },
  { title: 'Edit Candidate', back: 'arrow_back' },
  { title: 'Add Candidate - Bulk Upload', back: 'arrow_back' },
  { title: 'Candidates', back: 'menu' },
  { title: 'Reports', back: 'arrow_back' },
];

@Component({
  selector: 'app-ta',
  templateUrl: './ta.component.html',
  styleUrls: ['./ta.component.css'],
  providers: [NavBarService]
})
export class TAComponent implements OnInit, OnDestroy {

  currentPageNumber: number;
  roleStatus: boolean;
  onlyOneRole: Boolean;
  currentPageData: { title: string, back: string };
  backLink = '/employee';
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };
  initials = '';

  private subscriptions = [];
  onboardTab = false
  modalContent: string;
  modalCandidate: string;
  showVideos: any;
  vidName: string;
  @Input() backNavClicked: boolean;
  frmCandD:boolean = false;
  imageUrl: string = environment.imageUrl;
  constructor(
    protected localStorageService: LocalStorageService,
    private navBarService: NavBarService,
    private router: Router,
    private modalService: TaModalServiceService,
    private toastr: ToastsManager,
    private AuthService: AuthService,
    private sanitizer: DomSanitizer) {
    // if (window.location.origin !== 'http://localhost:8080') {
    var empData;
    empData = this.localStorageService.get('userInfo');
    this.empData = empData;
    if (this.empData['roles'].length > 1) {
      this.onlyOneRole = false;
    } else {
      this.onlyOneRole = true;
    }
    // console.log(this.empData, "userInfo Detailssssss")
    if (this.empData['fullName']) {
      this.initials = this.empData['fullName'].replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    } else {
      this.initials = 'LS';
    }

    let currentRole = this.localStorageService.get('userSession')
    if(currentRole !== 'COACH') {
      this.onboardTab = true
    } else {
      this.onboardTab = false

    }


    console.log('initials: ' + this.initials);
    navBarService.currentPage.subscribe((val: number) => {

      if (val) {
        //alert(val)
        this.currentPageNumber = val;
        this.currentPageData = taPages[this.currentPageNumber];
      }
      else {
        //alert(val)

        this.currentPageNumber = 0;
        this.currentPageData = taPages[this.currentPageNumber];
        this.backLink = '/employee';
        //this.currentPageData = taPages[this.currentPageNumber];
      }


      if ([ 1, 2, 3, 4,6].includes(this.currentPageNumber)) {

        let sessonRole = this.localStorageService.get('userSession');
        console.log(sessonRole);
        if(sessonRole === 'HEAD_COACH' || sessonRole === 'HEAD_COACH'){
          this.backLink = '/ta';

        }else {
          this.backLink = '/ta';

        }
       this.currentPageData = taPages[this.currentPageNumber];
        // console.log('check the title ---',this.currentPageData)
        // not sure what is this for
      } else if ([5, 6].indexOf(this.currentPageNumber) !== -1) {
        console.log('contained');
        this.backLink = '/employee';
        this.currentPageData = taPages[this.currentPageNumber];

      } else {
        this.backLink = '/employee';
        this.currentPageData = taPages[this.currentPageNumber];

      }

      console.log('getting page in parent: ' + val);
    });

    this.subscriptions.push(this.modalService.modal_content.subscribe(content => this.modalContent = content));
    this.subscriptions.push(this.modalService.candidate.subscribe(candidate => this.modalCandidate = candidate));

    this.subscriptions.push(this.modalService.modal_accepted.subscribe(accepted => {
      if (accepted) {
        if (this.modalContent == MODAL_CONTENT.REJECT) {
          this.approve('TA_REJECTED');
        } else if (this.modalContent == MODAL_CONTENT.SELECT) {
          this.approve('TA_APPROVED');
        }
      }
    }));
    console.log(this.backNavClicked);
  }

  approve(status) {
    this.AuthService.candidateStatusUpdate({ candidateStatus: status, fromId: this.empData.userInfoMstrId, toId: this.modalCandidate }).then(responseData => {

      var responseDataCheck = responseData

      if (responseData['status'] == 'success') {

        if (status == 'TA_REJECTED') {
          this.toastr.success("Candidate rejected from the PlayGround");
          /*this.router.navigate(['/ta']);*/
          this.onRefresh();
        } else {
          this.toastr.success("Candidate approved for the Playground");
         /*this.router.navigate(['/ta']);*/
          this.onRefresh();
        }
      } else {
        console.log(responseData, 'Else case Canditates Approval ')
      }

    }).catch(err => {
      console.log(err)
    });
    this.navBarService.isClickedConfirmedEvent(true);
  }

  onRefresh() {
    console.log('On live load data')
    this.router.navigate(['/ta'], { queryParams: { 'param': 'reload'  } });
  }


  ngOnInit() {
    console.log("on init --- currentPageData -- ",this.currentPageData);
    this.navBarService.setCurrentPage(0);
    console.log('back nav bt --- ',this.backNavClicked);
  }

  ngOnDestroy() {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }

  navigateBack() {
    this.router.navigate([this.backLink]);
    this.currentPageData = taPages[this.currentPageNumber];
    //console.log('navigate hua ki??? ',this.currentPageData);
  }
  public menuItemsArray: any[] = [
    // {"title":"Account","link":"#", "id":"account"},
    // {"title":"Report","link":"#", "id":"report"},
    {"title":"Help","link":"#", "id":"help",
    "subItems":[
                // {"title":"Candidate","link":"#", "embed":"Candidate.mov", "id":"candidateV", "name":"Candidate Help Video"},
                {"title":"Talent Acquisition","link":"#", "embed":"TA-Add+and+Edit+the+candidate.mov", "id":"talentV", "name":"Talent Acquisition Help Video"},
                // {"title":"Employee","link":"#", "embed":"Employee+intro+and+capability+assessment.mov", "id":"employeeV", "name":"Employee Help Video"},
               ]
    },
  ];

  public onMenuClose(){
    console.log("menu closed");
  }
  public onMenuOpen(){
    console.log("menu Opened");
  }
  public onItemSelect(item:any){
    console.log(item);
    this.vidName = item.name;
    this.showVideos = item.embed;
    document.getElementById('openVideoModalButton').click();
  }
  
  getEmbedURL(url){
    return ('https://pgvideos.altimetrik.com/'+this.showVideos);
  }
  vidStop(videoplayer){
    videoplayer.pause();
  }
  changeRole(status){
    this.roleStatus = status;
  }
  closeNavDetails(event){
    this.roleStatus = event;
  }

  openFeedModal(e){
    console.log(e);
    if(e == true){
      this.frmCandD = e
    }
  }

  closeFdModal(e){
    console.log(e);
    if(e == false){
      this.frmCandD = e;
      console.log(this.frmCandD);
    }
  }
}
