import { Component, OnInit, Output, EventEmitter, ViewChild, ViewContainerRef } from '@angular/core';
import { Element } from '@angular/compiler';
import { ElementRef } from '@angular/core/src/linker/element_ref';
import { EmployeeNavBarService } from 'app/employee/employee-dashboard/employee-nav-bar.service';
import { AuthService } from 'app/services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { Observable } from 'rxjs/Observable';
import { SkillsResponse } from 'app/models/skills.model';
import { DirectoryBundleResponse } from 'app/models/directory-bundle-model';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { EmployeeSandboxProgressIconComponent } from 'app/employee/employee-sandbox-progress-icon/employee-sandbox-progress-icon.component';
import { Subject } from 'rxjs/Subject';
/*import { Navigation } from 'selenium-webdriver';*/
import { Router } from '@angular/router';
import { ProgressStateSetupWorkspaceService } from 'app/employee/employee-dashboard/employee-sandbox/progress-state-setup-workspace.service';
import { state, ResponseSetupWorkSpace } from 'app/models/sandbox-progress.model';
import { environment } from '../../../../environments/environment.dev';

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



  public launchOpen = false;
  public cardsCategories: Array<{
    selected: boolean,
    title: string,
    bundleId: string,
    directoryId: string,
    itemTecnologies: Array<string>
  }>;
  employee: {
    accessToken: any,
    adId: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };

  launchData = false;
  public availableCreate: boolean;

  WorkspaceData: any;
  imageUrl: string = environment.imageUrl;
  constructor(private employeeNavBarService: EmployeeNavBarService,
    protected localStorageService: LocalStorageService,
    private authService: AuthService,
    private toastr: ToastsManager,
    private route: Router,
    private stateService: ProgressStateSetupWorkspaceService,
  ) {

    this.cardsCategories = [];
    employeeNavBarService.setCurrentPage(4);
    // if (window.location.origin !== 'http://localhost:8080') {
    this.employee = this.localStorageService.get('userInfo');
    // } else {
    //   this.employee = {
    //     accessToken: '',
    //     loginType: '',
    //     adId: 'tkhader81',
    //     fullName: 'Sabash LS',
    //     firstName: 'sabash',
    //     userInfoMstrId: 2,
    //     roleName: 'HEAD_COACH',
    //     roles: [1],
    //     skills: [1, 2],
    //     location: 1
    //   };
    // }
  }

  ngOnInit() {
    Promise.all([
      this.authService.getAllAwsDirectoryBundle(),
      this.authService.getAllSkill()])
      .then(response => {

        const skillsResp = response[1] as SkillsResponse,
          directoryBundle = response[0] as DirectoryBundleResponse;
        this.cardsCategories = directoryBundle.pgAwsDirectoryBundleList
          .map(val => {


            return {
              bundleId: val.bundleId,
              directoryId: val.directoryId,
              selected: false,
              title: val.pgSkillTrackMstr.skillTrackName,
              itemTecnologies: skillsResp.pgSkillTrackDtlsList
                .filter(skill => skill.pgSkillTrackMstr.skillTrackMstrId === val.pgSkillTrackMstr.skillTrackMstrId)
                .map(sel => sel.skillTrackDtlsName)
            };
          });
      });


    this.stateService.ProgressIconComponent.subscribe(r => {
      this.availableCreate = r.state === state.Completed || r.state !== state.InProgress;
    });


  }
  hoverActive(card: HTMLElement) {
    card.classList.toggle('card-sandbox-hover-active');
    card.children.namedItem('inner-card-flow')
      .classList.toggle('card-sandbox-major-hover-active');
  }
  selectActive(card: HTMLElement, cardObj, index) {
    this.cardsCategories.filter(c => c.selected)
      .forEach(cObj => {
        cObj.selected = false;
      });

    for (let i = 0; i < card.parentElement.children.length; i++) {
      const cardNoSelect = card.parentElement.children[i];
      cardNoSelect.classList.remove('card-sandbox-active');
    }

    card.classList.toggle('card-sandbox-active');
    cardObj.selected = true;
    this.WorkspaceData = cardObj;
  }


  setupWorkspace() {

    if (this.cardsCategories.filter(c => c.selected).length === 1 && this.WorkspaceData) {

      this.WorkspaceData['adId'] = this.employee['adId'];
      this.launchOpen = true;

      this.stateService.setupProcessWorked.next({ show: true, state: state.InProgress, data: { createdTime: Date.now() } });


      this.authService.setupWorkSpace({
        sname: this.employee['adId'],
        sbundleId: this.WorkspaceData['bundleId'],
        sdirId: this.WorkspaceData['directoryId']
      }).then(resp => {
        resp = resp as ResponseSetupWorkSpace;
        if (!resp.registrationCode) {
          this.stateService.setupProcessWorked.next({ show: false, state: state.Error, data: { createdTime: Date.now() } });
          this.toastr.error('Something went wrong in the Setup Workspace...');
        } else {
          this.stateService.setupProcessWorked.next({ show: true, state: state.Completed, data: resp });
          // this.toastr.success('WorkSpace Created Successfully');
        }
      }).catch(err => {
        this.stateService.setupProcessWorked.next({ show: false, state: state.Error, data: { createdTime: Date.now() } });
        this.toastr.error('Something went wrong in the Setup Workspace...');
        console.log(err);
      });
    } else {
      this.toastr.error('Please select skill');
    }
  }
}
