import { Component, OnInit, Input  } from '@angular/core';
import { UsecaselistService } from './usecaselist.service'
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { environment } from '../../../../../environments/environment.dev';
import  _ from 'lodash';
// import { $ } from 'protractor';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

@Component({
  selector: 'app-usecase-list',
  templateUrl: './usecase-list.component.html',
  styleUrls: ['./usecase-list.component.scss']
  
})

export class UsecaseListComponent implements OnInit {

  usecaseList: any[];
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  img_path_one = environment.imageUrl+'/assets/img/';
  addNewcase : boolean;
  detailDescpage : boolean = false;
  usecaselist: Usecaselist [];
  theTechDetails: any;
  roles: any;
  usecaseclickedId: number;
  ROLES = ['Technical','Business'];
  // , "Whiteboard Scenario"];

  role:string;
  businessCaseUC: boolean;
  technicalDesc :any;
  businessCaseList: any;
  usecaseclickedTitle: string;
  whiteboardList: any;
  topRowSkills: any;
  othIcons: boolean;
  editUsecaseForm: boolean;
  ucDetail: any;
  uctoEdit: any;
  isEdit: any;
  loading: boolean = false;
  useCaseId: number;
  colors = ["#009587","#01BCD5", "#663AB7","#E6A9E6", "#3F51B5", "#F8A9CA", "#6FDCDE", "#F2D2CD", "#F2CCDB", "#BFE2F5", "#D8D0F7", "#6FDCDE", "#EC8ECC","#E6A9E6", "#3F51B5", "#F8A9CA", "#6FDCDE", "#F2D2CD", "#F2CCDB", "#BFE2F5", "#D8D0F7", "#009587","#01BCD5", "#663AB7","#E6A9E6", "#3F51B5", "#F8A9CA", "#6FDCDE", "#F2D2CD", "#F2CCDB", "#BFE2F5", "#D8D0F7"];
  mycolor: any;
  deleteUcDetails: any;
  dialogData: any;
  //Base Urls
  private baseURL= environment.apiUrl;
  whiteboardUC: boolean = false;

  constructor(private usecaselistservice: UsecaselistService, private http:Http, private router: Router, private recucforEdit: UsecaselistService,  private toastr: ToastsManager){
    this.theTechDetails = {};
  }
  ngOnInit() {
    
    this.othIcons = false;
    this.addNewcase = false;
    this.usecaselistservice.getUsecaselist().subscribe((usecaselist) => {
      //  console.log("usecase list" +JSON.stringify(usecaselist));
      this.usecaselist = usecaselist;
      for(let i=0; i<this.usecaselist.length; i++){
        // this.usecaselist[i] = 
        this.randomColor();
      }
    });

    this.dialogData = { title: 'Usecase Delete Confirmation', text: 'Would you like to delete this Usecase from the list?' };
  }
  
  Initials(xitem: string) {
    if (xitem) {
      return xitem.replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    }
  }

  viewDetailTechUsecase(itemId, itemTitle){
    this.usecaseclickedId = itemId;
    this.usecaseclickedTitle = itemTitle;
    this.loading = true;
    const req = this.http.get(this.baseURL +'orchestrate/common-getAllMiniUsecasesBySkill/'+itemId)
    .subscribe(
      res => {
        this.technicalDesc = _.orderBy(res.json().useCaseList,['id'],[ 'desc'])
        // console.log(this.technicalDesc);
        let topTiles = [];
        let topSkills= [];
        this.technicalDesc.forEach(usrSkills => {
        usrSkills.pgUsecaseSkillMapping.forEach(pgSkillMapping => {
          topSkills.push({skillName:pgSkillMapping.pgSkillTrackDtls.skillTrackDtlsName,skillId:pgSkillMapping.pgSkillTrackDtls.skillTrackDtlsId})
          });
        });
        this.businessCaseUC = false;
        this.whiteboardUC = false;
        topSkills= _.uniqBy(topSkills,'skillName');
        this.topRowSkills = topSkills;
        // console.log("top row skills ---" +this.topRowSkills);
      },
      err => {
        console.log("error occured");
        this.toastr.error(err);
      }
    );
    this.loading=false;
    this.detailDescpage = true;
  }
  
  gotoTilespage(){
    this.detailDescpage = false;
  }

 
  addNewUsecase(){
    console.log("Create New Usecase - form");
    
    this.editUsecaseForm = false;
    this.addNewcase = true;
    console.log(this.addNewcase);
  }

  formCancelled(msg){
  this.addNewcase = false;
  this.editUsecaseForm = false;
  this.usecaselistservice.getUsecaselist().subscribe((usecaselist) => {
    this.usecaselist = usecaselist;
  });
  }

  formCancelledEdit(msg){
    this.addNewcase = false;
    this.editUsecaseForm = false;
    this.detailDescpage = true;
  }

  showOnlyRespSkillUC(id){
    console.log("clicked top skill -- "+id)
  }

  receiveRole($event){
    console.log($event);
    this.role = $event;
    if(this.role == 'Technical'){
      this.businessCaseUC = false;
      this.whiteboardUC = false;
      let topTiles = [];
        let topSkills= [];
        this.technicalDesc.forEach(usrSkills => {
        usrSkills.pgUsecaseSkillMapping.forEach(pgSkillMapping => {
          topSkills.push({skillName:pgSkillMapping.pgSkillTrackDtls.skillTrackDtlsName,skillId:pgSkillMapping.pgSkillTrackDtls.skillTrackDtlsId})
          });
        });
        this.businessCaseUC = false;
        topSkills= _.uniqBy(topSkills,'skillName');
        this.topRowSkills = topSkills;
    }
    else if(this.role == 'Business'){
      this.businessCaseUC = true;
      this.whiteboardUC = false;
      const req = this.http.get(this.baseURL+'orchestrate/common-getAllMainUsecasesBySkill/'+this.usecaseclickedId)
    .subscribe(
      res => {
       this.businessCaseList = _.orderBy(res.json().useCaseList,['id'],[ 'desc'])
         console.log(this.businessCaseList);
         let topTiles = [];
        let topSkills= [];

        this.businessCaseList.forEach(usrSkills => {
        usrSkills.pgUsecaseSkillMapping.forEach(pgSkillMapping => {
          topSkills.push({skillName:pgSkillMapping.pgSkillTrackDtls.skillTrackDtlsName,skillId:pgSkillMapping.pgSkillTrackDtls.skillTrackDtlsId})
        });
        });
        topSkills= _.uniqBy(topSkills,'skillName');
        this.topRowSkills = topSkills;
      },
      err => {
        console.log("error occured");
      }
    );
    }
    // else if(this.role == 'Whiteboard Scenario'){
    //   this.whiteboardUC = true;
    //   this.whiteboardList = [];
    // }
  }

  editUsecase($event){
    this.ucDetail = $event;
    console.log(this.ucDetail);
    if(this.ucDetail != null || undefined){
      this.usecaselistservice.getQueAndAns(this.ucDetail.id).subscribe(resp => {
        console.log(resp);
        this.ucDetail.singleSelectQuestions = resp.singleSelectQuestions;
        this.ucDetail.multipleSelectQuestions = resp.multipleSelectQuestions;
        this.ucDetail.customQuestions = resp.customQuestions;
        this.ucDetail.rating = resp.rating;
      })
      this.detailDescpage = false;
        this.addNewcase = false;
        this.editUsecaseForm = true;

       // this.isEdit = this.uctoEdit;
    }
    else{
      console.log(' Not yet cliked edit uc');
    }
  }

  deleteUsecase($event){
    console.log(this.technicalDesc);
    document.getElementById("delUcModal").click();
    this.deleteUcDetails = $event;
  }
  confirmDelete(){
    console.log(this.deleteUcDetails);
    this.useCaseId = this.deleteUcDetails.id;
    let eventMtr: number;
    let itemId: number;
    eventMtr = this.deleteUcDetails.eventMstrId;
    itemId = this.deleteUcDetails.skillTrackMstrId;
    const req = this.http.delete(this.baseURL +'orchestrate/admin-deleteUseCase/'+this.useCaseId)
    .subscribe(
      (res:any) => {
      console.log(res);
      res = JSON.parse(res._body);
      console.log("JSON res --- ",res);
      if(res.errorBean){
        console.log("res.errorBean --- ",res.errorBean);
        this.toastr.error(res.errorBean.errorMessage);
      }
      else{
        this.toastr.success('Usecase Deleted successfully');
        if(eventMtr == 2){
        this.viewDetailTechUsecase(itemId, null);
        }
        else if(eventMtr == 3){
          const req = this.http.get(this.baseURL+'orchestrate/common-getAllMainUsecasesBySkill/'+itemId)
          .subscribe(
            res => {
            this.businessCaseList = _.orderBy(res.json().useCaseList,['id'],[ 'desc'])
              // console.log(this.businessCaseList);
            },
            err => {
              console.log("error occured");
            }
          );
          }
        }
      },
    err => {
      console.log("error occured");
      this.toastr.error(err);
    }
  );
  }

  refreshUsecase($event){
    console.log('edited usecase det req -- ',$event);
    this.useCaseId = $event.id;
    let eventMtr: number;
    let itemId: number;
    eventMtr = $event.eventMstrId;
    itemId = $event.skillTrackMstrId;
    if(eventMtr == 2){
      this.viewDetailTechUsecase(itemId, null);
      }
      else if(eventMtr == 3){
        const req = this.http.get(this.baseURL+'orchestrate/common-getAllMainUsecasesBySkill/'+itemId)
    .subscribe(
      res => {
       this.businessCaseList = _.orderBy(res.json().useCaseList,['id'],[ 'desc'])
        // console.log(this.businessCaseList);
      },
      err => {
        console.log("error occured");
      }
    );
      }

  }
  // getRandomColor() {
  //   var letters = '0123456789ABCDEF';
  //   var color = '#';
  //   for (let i = 0; i < 6; i++) {
  //     color += letters[Math.floor(Math.random() * 16)];
  //   }
  //   console.log(color)
  //   return color;
  // }
  randomColor(){
    return  this.colors[Math.floor(Math.random() * (this.colors.length-1)) + 0];
  }
}

interface Usecaselist {
  id: number,
  title: string,
  subincludes: [{
      id: number,
      subtitle: string
}],
  tech_usecase: number,
  busi_usecase: number
}
