import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../../../services/auth.service';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import _ from "lodash";
import { environment } from '../../../../../environments/environment.dev';

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

  addNewAssesment: boolean;
  caList: boolean;
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  prefs = [
    { name: 'Option 1' },
    { name: 'Option 2' }
  ];
  UpdateBtn = false
  userForm: FormGroup;
  assessments = [];
  errMsg = '';
  dismiss = 'none';
  Skills: string;
  dialogData: any;
  caDetEdit: any;
  idToDelete: number;
  myColor = ["#009587", "#01BCD5", "#663AB7", "#E6A9E6", "#3F51B5", "#F8A9CA", "#6FDCDE", "#F2D2CD", "#F2CCDB", "#BFE2F5", "#D8D0F7", "#6FDCDE", "#EC8ECC", "#009587", "#01BCD5", "#663AB7", "#E6A9E6", "#3F51B5", "#F8A9CA", "#6FDCDE", "#F2D2CD", "#F2CCDB", "#BFE2F5", "#D8D0F7", "#6FDCDE", "#EC8ECC"];
  colors = ["#009587", "#01BCD5", "#663AB7", "#E6A9E6", "#3F51B5", "#F8A9CA", "#6FDCDE", "#F2D2CD", "#F2CCDB", "#BFE2F5", "#D8D0F7", "#6FDCDE", "#EC8ECC"];
  detailAssPg: boolean = false;
  detailedAssesment: any;
  topRowSkillDets: any = [];
  assessmentlickedTitle: string;
  activefilter: string;
  filterSkill: string;
  previousfilterSkill: string;
  filterclickedCount: number = 0;
  detailedAssesmentCopy: any;
  deletedIdFromMstr: number;
  deletedFromMstrName: string;

  constructor(private fb: FormBuilder,
    private AuthService: AuthService,
    private toastr: ToastsManager) {

    this.getAssessments()
    this.getAllSkills()
  }

  ngOnInit() {
    this.caList = true;
    this.errMsg = ''
    this.UpdateBtn = false
    this.dialogData = { title: 'Capability Assessment Confirmation', text: 'Would you like to delete this Capability Assessment from the list?' };
    this.activefilter = 'initial';
  }

  Initials(xitem: string) {
    if (xitem) {
      return xitem.replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    }
  }

  randomColor() {
    return this.colors[Math.floor(Math.random() * (this.colors.length - 1)) + 0];
  }
  addAssesment() {
    this.caList = false;
    this.addNewAssesment = true;
    this.errMsg = ''
    this.UpdateBtn = false;
    //this.navBarService.setCurrentPage(2);
    this.userForm = this.fb.group({
      directoryId: ['', Validators.required],
      bundleId: ['', Validators.required],
      //skillTrackMstrId : ['Select'],
      id: ['', Validators.required]
    });
  }

  getAssessments() {
    this.AuthService.getAllCapabilityAssessments().then(resp => {
      this.assessments = resp;
      // this.tableData.rows = this.assessments.map(function (item, index, array) {
      //   return [item.pgSkillTrackMstr.skillTrackName  || 'No skill available', item.assessmentId, item.assessmentDesc];
      // });
    }).catch(err => {
      console.log(err)
    })
  }

  getAllSkills() {
    this.AuthService.getAllSkillTrackMstr().then(resp => {
      console.log(resp, 'getAllSkillTrackMstr')
      this.Skills = resp.pgSkillTrackMstr
    }).catch(err => {
      console.log(err)
    })
  }

  deleteAssesment(e) {
    console.log('Deleting item: ', JSON.stringify(e));
    if (e.isDelete) {
      document.getElementById("delConfModal").click();
      //this.confirmDelete
    }
    this.idToDelete = e.id;
    this.deletedIdFromMstr = e.skillTrackMstrId;
    this.deletedFromMstrName = e.skillTrackName;
  }
  confirmDelete() {
    console.log(this.idToDelete);
    this.AuthService.getDeleteAssessmentId(this.idToDelete).then(resp => {
      if (resp.status == 'error') {
        this.toastr.error(resp.message);
      } else {
        this.toastr.success(resp.successMessage);
        this.getAssessments();
        this.viewDetailAssment(this.deletedIdFromMstr, this.deletedFromMstrName)
      }
    }).catch(err => {
      console.log(err)
    })
  }
  editAssesment(e) {
    console.log('Editing item:', JSON.stringify(e));
    this.UpdateBtn = true;
    this.caList = false;
    this.addNewAssesment = false;
    this.caDetEdit = e;
  }

  formCancelled(e) {
    console.log(e);
    this.caList = true;
    this.detailAssPg = false;
    this.getAssessments();
  }
  
  editFormCancelled(e){
    console.log('edit form data ---',e);
    this.detailAssPg = true;
    this.caList = true;
    this.viewDetailAssment(e.skillTrackMstrId, e.skillTrackName);
  }

  viewDetailAssment(id, name) {
    // console.log(id);
    this.assessmentlickedTitle = name;
    //getCapabilityAssessmentsBySkill
    this.AuthService.getCapabilityAssessmentsBySkill(id).then(resp => {
      if (resp.status == 'error') {
        this.toastr.error(resp.message);
      } else {
        // this.toastr.success(resp.successMessage);
        this.detailedAssesment = resp.pgAssessmentDtls;
        this.detailedAssesmentCopy = resp.pgAssessmentDtls;
        // this.topRowSkillDets = resp.pgAssessmentDtls.skillTrackDtls;
        this.detailedAssesment.forEach(element => {
          element.pgAssessmentSkillMapping.forEach(skill => {
            this.topRowSkillDets.push({skillTrackDtlsName:skill.pgSkillTrackDtls.skillTrackDtlsName, skillTrackDtlsId:skill.pgSkillTrackDtls.skillTrackDtlsId});
            this.topRowSkillDets = _.uniqBy(this.topRowSkillDets,'skillTrackDtlsId')
          });
        });
        console.log("this.topRowSkillDets --- ",this.topRowSkillDets );
        // console.log('Detailed assmnt info', JSON.stringify(this.detailedAssesment));
      }
    }).catch(err => {
      console.log(err)
    })
    this.detailAssPg = true;
  }

  gotoTilespage() {
    this.detailAssPg = false;
    this.topRowSkillDets = [];
  }

  showOnlyRespSkillUC(data) {
    // detailedAssesment
    
    let a = [];
    console.log(this.detailedAssesment)
    this.filterSkill = data;
    if (this.filterSkill !== this.previousfilterSkill || this.filterclickedCount === 0) {
      this.filterclickedCount += 1;
      this.activefilter = data;
      this.previousfilterSkill = this.filterSkill;
      // this.primaryusecase = this.primaryusecasecopy.filter(x => x.assessmentStatus.toLowerCase().trim() === this.filterword.toLowerCase().trim());
      this.detailedAssesmentCopy.filter(obj => obj.pgAssessmentSkillMapping.filter(data => {
        if (data.pgSkillTrackDtls.skillTrackDtlsName.toLowerCase().includes(this.filterSkill.toLowerCase())) {
          a.push(obj)
        }
      }
      ))
      this.detailedAssesment = a;
    }
    else {
      this.filterclickedCount = 0;
      this.activefilter = '';
      this.detailedAssesment = this.detailedAssesmentCopy;
    }

  }
}
