import { Component, OnInit, Input, Output, EventEmitter, Pipe, PipeTransform, ViewChild, ViewEncapsulation, Directive } from '@angular/core';
import { MatSelectModule } from '@angular/material/select';
import { UsecaselistService } from '../usecaselist.service'
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormsModule, FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { MatCheckboxModule } from '@angular/material';
import _ from "lodash";
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { environment } from '../../../../../../environments/environment.dev';
import { LocalStorageService } from 'angular-2-local-storage';


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

// @Directive({
//   selector: 'ngInit',
//   exportAs: 'ngInit'
// }) 
export class UsecaseFormComponent implements OnInit {
  @Input() ucDetail;
  @Input() isEdit;
  testdata: any;
  loopData: any;
  expLevel: Explevel [];
  usecaseType: any;
  selectedSkillValues: any;
  ck: string;
  checked: boolean;
  formTitle: string;
  editUcDisabled: boolean = false;
  reqData: any;
  name: string;
  
  skilltrackResponse: Skilltrackdetails [];
  // skillmasterSelected: any;
  // usecasesCheckedBoxes: any;
  // usecasetypeSelected: any;
  // experienceSelected: any;
  // newusecaseTitle: string;
  newucFormdet: any;
  editucFormdet: any = {};
  skillDetail: any;
  // usecaseEditorContent: string;
  sandBoxSelected: any;
  sandboxCheckbox = false;
  dispAvailableSandbox = false;
  testCheckbx : any;
  selectedtrackChecks: any;
  skillArr : any = [];
  errMsg = '';
  answer_option: any = [];
  qnrBtns: boolean = true;
  qnrFormData: boolean = false;
  closeAddMore: boolean = false;
  imgPath = environment.imageUrl+'/assets/img/admin/';
  qnrSIndex:number = 0;
  qnrMIndex:number = 0;
  qnrRIndex:number = 0;
  //isEdit: boolean = false;

  @Output() cancelEvent = new EventEmitter();
  @Output() updateEvent: EventEmitter<any> = new EventEmitter();
  //@Output() successEvent = new EventEmitter();
  //@Input() skillTrackDetails;

  // @Input() ngInit;
  singleSelectQnr: boolean = false;
  multipleSelectQnr: boolean = false;
  customQnrBlock: boolean = false;
  questionnairedata = {
    singleSelectQuestions: [
      {
        question: null,
        answers: [
          {
            option: null,
            optionId: null
          }
        ],
        rating: null,
        questionId: null
      }
    ],
  };
  questionnairemultiSelectdata = {
    multipleSelectQuestions: [
      {
        question: null,
        answers: [
          {
            option: null,
            optionId: null
          }
        ],
        rating: null,
        questionId: null
      }
    ]
  };
  questionnaireCustomdata = {
    customQuestions: [
      {
        question: null,
        questionId: null,
        rating: null,
        answers: null
      }
    ]
  };
  
  singleSelectForm: FormGroup;
  multiSelectForm: FormGroup;
  customQnrForm: FormGroup;

  cancelForm(){
  this.cancelEvent.emit('true');
  }

  public editor;
  public usecaseEditorContent = `<h3>Usecase Description</h3>`;
  public editorOptions = {
    placeholder: "insert content..."
  };
  marked = false;
  theCheckbox = false;

  
  toggleVisibility(e){
    this.marked= e.target.checked;
  }

  //Base Urls
  private baseURL= environment.apiUrl

  constructor(private usecaselistservice: UsecaselistService, private http:HttpClient,  private toastr: ToastsManager, private formBuilder: FormBuilder, private fb: FormBuilder, protected localStorageService: LocalStorageService) {
    this.newucFormdet = {};
    this.singleSelectForm = this.fb.group({
      singleSelectQuestions: this.fb.array([]),
    })
    this.setSingleQuestionnaire();
   
   this.multiSelectForm = this.fb.group({
    multipleSelectQuestions: this.fb.array([]),
    })
    this.setMutipleeQuestionnaire();

    this.customQnrForm = this.fb.group({
      customQuestions: this.fb.array([]),
    })
    this.setCustomQuestionnaire();
    
    // var reqData = {};
    this.reqData = this.localStorageService.get('userInfo');
    console.log(this.reqData);
    this.name = this.reqData['fullName'];
    console.log(this.name);

 }
  onEditorBlured(quill) {
    console.log('editor blur!', quill);
  }
 
  onEditorFocused(quill) {
    console.log('editor focus!', quill);
  }
 
  onEditorCreated(quill) {
    this.editor = quill;
    console.log('quill is ready! this is current quill instance object', quill);
  }
 
  onContentChanged({ quill, html, text }) {
    console.log('quill content is changed!', quill, html, text);
  }

  ngOnInit() {
    this.usecaselistservice.getAllSkillTrackDetails().subscribe((skilltrackdetails) => {
      var customSkill = []
      var skills = _.uniqBy(skilltrackdetails.pgSkillTrackDtlsList,'pgSkillTrackMstr.skillTrackName')
      var masterSkills = _.uniqBy(_.flattenDeep(skills.map(i => i.pgSkillTrackMstr)))
      masterSkills.forEach(usrSkills => {
        var dtlsSkill = skilltrackdetails.pgSkillTrackDtlsList.filter(item => item.pgSkillTrackMstr.skillTrackName == usrSkills.skillTrackName)
        var skillTrackDtlsName = _.uniqBy(_.flattenDeep(dtlsSkill.filter(i => {return {id : i.skillTrackDtlsId, name : i.skillTrackDtlsName}})))
        customSkill.push({skillMaster:usrSkills,skillTrackDtls :dtlsSkill,skillTrackDtlsName:skillTrackDtlsName});
      });
      console.log(customSkill);
      this.skilltrackResponse = customSkill;
      console.log(this.ucDetail);
      if(this.isEdit){
        this.formTitle = "Edit UseCase";
        this.editUcDisabled = true;
        this.qnrBtns = false;
        this.newucFormdet.skillTrackMstrId = this.ucDetail.skillTrackMstrId;
        this.newucFormdet.usecaseDesp = this.ucDetail.usecaseDescription;
        this.newucFormdet.useCaseTitle = this.ucDetail.usecaseTitle;
        this.newucFormdet.experienceLevelId = this.ucDetail.pgExperienceLevel.experienceLevelId;
        this.newucFormdet.rating = this.ucDetail.rating;
        this.newucFormdet.passMarks = this.ucDetail.passMarks;
        this.newucFormdet.eventMstrId = this.ucDetail.eventMstrId;
        this.newucFormdet.usecaseId = this.ucDetail.id;
        if(this.ucDetail.pgUsecaseSkillMapping && this.ucDetail.pgUsecaseSkillMapping.length != 0){
          this.newucFormdet.skillTrackName = this.ucDetail.pgUsecaseSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackName;
          this.newucFormdet.skillTrackMstrId = this.ucDetail.pgUsecaseSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackMstrId;
          this.onSkillMaster(null, this.newucFormdet.skillTrackMstrId);
          this.skillArr = this.ucDetail['pgUsecaseSkillMapping'].map((skillMap)=>skillMap['pgSkillTrackDtls']['skillTrackDtlsId'])
        }
        
        if(this.ucDetail.singleSelectQuestions){
          // if(!this.ucDetail.singleSelectQuestions[0].question){
          //   delete this.ucDetail.singleSelectQuestions;
          // }
          // else{
          this.qnrFormData = true;
          this.singleSelectQnr = true;
          this.questionnairedata.singleSelectQuestions = this.ucDetail.singleSelectQuestions;
          console.log(this.questionnairedata.singleSelectQuestions);
          this.setSingleQuestionnaire();
          // }
        }
        if(this.ucDetail.multipleSelectQuestions){
          // if(!this.ucDetail.multipleSelectQuestions[0].question){
          //   delete this.ucDetail.multipleSelectQuestions;
          // }
          // else{
          this.qnrFormData = true;
          this.multipleSelectQnr = true;
          this.questionnairemultiSelectdata.multipleSelectQuestions = this.ucDetail.multipleSelectQuestions;
          this.setMutipleeQuestionnaire();
          // }
        }
        if(this.ucDetail.customQuestions){
          // if(!this.ucDetail.customQuestions[0].question){
          //   delete this.ucDetail.customQuestions;
          // }
          // else{
          this.qnrFormData = true;
          this.customQnrBlock = true;
          this.questionnaireCustomdata.customQuestions = this.ucDetail.customQuestions;
          this.setCustomQuestionnaire();
          // }
        }
      }
      else{
        this.formTitle = "Create Usecase";
      }  
    });
    
    this.usecaselistservice.getExpLevel().subscribe((explevels) => {
      this.expLevel = explevels.pgExperienceList;
    });

  this.usecaseType =[
      {"id": 2, "type" : "TECHNICAL"},
      {"id": 3, "type" : "BUSINESS"},
      // {"id": 5, "type" : "WHITEBOARD SCENARIO"}
  ];

  var reqData = {};
  this.reqData = this.localStorageService.get('userInfo');
  this.name = this.reqData['fullName'];
}

selectTrackDtls(category, event) {
  var index = this.selectedtrackChecks.indexOf(event.target.value);
  if (event.target.checked) {
      this.selectedtrackChecks.push(event.target.value);
   } else {
      if (index !== -1) {
          this.selectedtrackChecks.splice(index, 1);
      }
  }
  console.log(this.selectedtrackChecks);
}

updateCheckedOptions(id, e){
  if(e.target.checked === true ){
  this.skillArr.push(id);
  }
  else{
    this.skillArr.splice(this.skillArr.indexOf(id), 1)
  }
  this.newucFormdet.skillTrackDtlsId = this.skillArr;
  console.log(this.newucFormdet.skillTrackDtlsId );
}

submitTheForm(){
  console.log("clicked the create btn... ");
  this.newucFormdet.singleSelectQuestions = this.singleSelectForm.value.singleSelectQuestions;
  this.newucFormdet.multipleSelectQuestions = this.multiSelectForm.value.multipleSelectQuestions;
  this.newucFormdet.customQuestions = this.customQnrForm.value.customQuestions;
  this.newucFormdet.loggedInUser = this.name;
  this.errMsg = ''
  if(this.newucFormdet.singleSelectQuestions[0].question == null){
    delete this.newucFormdet.singleSelectQuestions;
  }
  else if(this.newucFormdet.singleSelectQuestions.length > 0){
    // this.errMsg = '';
    this.newucFormdet.singleSelectQuestions.forEach(element => {
      console.log("singleSelectQuestions - ",element)
      if(!element.question){
        this.errMsg = 'Single Select Question cannot be empty';
      }
      element.answers.forEach(anselement => {
        
        if(!anselement.option){
          this.errMsg = 'Single Select Answer Option cannot be empty';
          console.log(this.errMsg);
        }
      });
    });
  }

  if(this.newucFormdet.multipleSelectQuestions[0].question == null){
    delete this.newucFormdet.multipleSelectQuestions;
  } 
  else if(this.newucFormdet.multipleSelectQuestions.length > 0){
    // this.errMsg = '';
    this.newucFormdet.multipleSelectQuestions.forEach(element => {
      if(!element.question){
        this.errMsg = 'Multi Select Question cannot be empty';
      }
      element.answers.forEach(anselement => {
        if(!anselement.option){
          this.errMsg = 'Multi Select Answer Option cannot be empty';
        }
      });
    });
  }

  if(this.newucFormdet.customQuestions[0].question == null){
    delete this.newucFormdet.customQuestions;
  }
  else if(this.newucFormdet.customQuestions.length > 0){
    // this.errMsg = '';
    this.newucFormdet.customQuestions.forEach(element => {
      if(!element.question){
        this.errMsg = 'Custom Question cannot be empty';
      }
    });
  }

  if((this.newucFormdet.skillTrackDtlsId == null || undefined) || (this.newucFormdet.skillTrackDtlsId.length < 0 )){
    this.errMsg = 'Select atleast one skill checkbox';
  }
  if((this.newucFormdet.customQuestions || this.newucFormdet.multipleSelectQuestions || this.newucFormdet.singleSelectQuestions) && (this.newucFormdet.rating == null || undefined)) {
    this.errMsg = 'Select the type of rating';
  }
  
  // else if (this.errMsg == '' || this.errMsg == null){
    if (!this.errMsg){
    console.log("Request Object for create usecase -- ",this.newucFormdet);
    const req = this.http.post(this.baseURL +'orchestrate/admin-addUseCase/', this.newucFormdet)
    .subscribe(
    (res:any) => {
        console.log(res);
        if(res.errorBean){
         if(res.errorBean.errorMessage == "Options are null in request"){
          this.toastr.error('Option field(s) cannot be empty');
        }
        else{
          res.errorBean.errorMessage
        }
        }
        else{
          this.toastr.success('Usecase Created successfully');
          this.newucFormdet = {};
          this.cancelEvent.emit('true');
        }
      },
      err => {
        console.log("error occured");
        this.toastr.error(JSON.stringify(err));
        this.errMsg = JSON.stringify(err.error.error.errorMessage);
      }
    );
  }
  console.log("test this.newucFormdet --- ",this.newucFormdet);
}

  onSkillMaster(e, data){
    console.log(e);
    console.log("data -- "+JSON.stringify(data));
    this.selectedSkillValues = data;
    console.log(this.selectedSkillValues);
  }

  updateUsecase(){
    this.errMsg = '';
    if(!this.newucFormdet.skillTrackDtlsId){
      this.newucFormdet.skillTrackDtlsId = this.skillArr;
    }
    this.newucFormdet.singleSelectQuestions = this.singleSelectForm.value.singleSelectQuestions;
    this.newucFormdet.multipleSelectQuestions = this.multiSelectForm.value.multipleSelectQuestions;
    this.newucFormdet.customQuestions = this.customQnrForm.value.customQuestions;
    
    if(this.newucFormdet.singleSelectQuestions[0].question == null){
      delete this.newucFormdet.singleSelectQuestions;
    }
    else if(this.newucFormdet.singleSelectQuestions.length > 0){
      // this.errMsg = '';
      this.newucFormdet.singleSelectQuestions.forEach(element => {
        console.log("singleSelectQuestions - ",element)
        if(!element.question){
          this.errMsg = 'Single Select Question cannot be empty';
        }
        element.answers.forEach(anselement => {
          
          if(!anselement.option){
            this.errMsg = 'Single Select Answer Option cannot be empty';
            console.log(this.errMsg);
          }
        });
      });
    }
    else {
      this.newucFormdet.singleSelectQuestions.forEach(element => {
        if(!element.questionId){
          delete element.questionId;
        }
      })
    }

    if(this.newucFormdet.multipleSelectQuestions[0].question == null){
      delete this.newucFormdet.multipleSelectQuestions;
    }
    else if(this.newucFormdet.multipleSelectQuestions.length > 0){
      // this.errMsg = '';
      this.newucFormdet.multipleSelectQuestions.forEach(element => {
        if(!element.question){
          this.errMsg = 'Multi Select Question cannot be empty';
        }
        element.answers.forEach(anselement => {
          if(!anselement.option){
            this.errMsg = 'Multi Select Answer Option cannot be empty';
          }
        });
      });
    }
    else {
      this.newucFormdet.multipleSelectQuestions.forEach(element => {
        if(!element.questionId){
          delete element.questionId;
        }
      })
    }

    if(this.newucFormdet.customQuestions[0].question == null){
      delete this.newucFormdet.customQuestions;
    }
    else if(this.newucFormdet.customQuestions.length > 0){
      // this.errMsg = '';
      this.newucFormdet.customQuestions.forEach(element => {
        if(!element.question){
          this.errMsg = 'Custom Question cannot be empty';
        }
      });
    }
    else {
      this.newucFormdet.customQuestions.forEach(element => {
        if(!element.questionId){
          delete element.questionId;
        }
      })
    }
    if((this.newucFormdet.customQuestions || this.newucFormdet.multipleSelectQuestions || this.newucFormdet.singleSelectQuestions) && (this.newucFormdet.rating == null || undefined)) {
      this.errMsg = 'Select the type of rating';
    }
    if (!this.errMsg){
      this.newucFormdet.loggedInUser = this.name;
      console.log('for edit --- '+JSON.stringify(this.newucFormdet));
      const req = this.http.put(this.baseURL +'orchestrate/admin-editUseCase/', this.newucFormdet)
      .subscribe(
        (res:any) => {
          console.log(res);
          // res = JSON.parse(res._body);
          if(res.errorBean && res.errorBean.errorMessage){
            this.toastr.error(res.errorBean.errorMessage);
          }
          else{
            this.toastr.success('Usecase Updated Successfully');
            this.updateEvent.emit(this.newucFormdet);
            console.log('for edit after success  --- '+JSON.stringify(this.newucFormdet));
            this.cancelEvent.emit('true');
            this.newucFormdet = {};
          }
        },
        err => {
          console.log("error occured");
          console.log(err);
          this.toastr.error(JSON.stringify(err));
        }
      );
    }
  }
  
  addMoreQnr(){
    this.qnrBtns = true;
    this.closeAddMore = true;
  }

  showSingleChoiceQnr() {
    this.qnrBtns = false;
    this.qnrFormData = true;
    this.singleSelectQnr = true;
    console.log('this.qnrSIndex --- ',this.qnrSIndex);
    if(this.isEdit && this.ucDetail.singleSelectQuestions){
      this.qnrSIndex = 1;
    }
    if (this.qnrSIndex>0){
    let control = <FormArray>this.singleSelectForm.controls.singleSelectQuestions;
    control.push(
      this.fb.group({
        question: [''],
        answers: this.fb.array([]),
        rating: [''],
        questionId: ''
      })
    )
    }
    this.qnrSIndex = this.qnrSIndex+1;
    console.log('this.qnrSIndex after complete --- ',this.qnrSIndex);
  }

  deleteSingleChoiceQnr(index) {
    let control = <FormArray>this.singleSelectForm.controls.singleSelectQuestions;
    control.removeAt(index)
  }

  addNewSingleChoiceAns(control) {
    control.push(
      this.fb.group({
        option: [''],
        optionId: ''
      }))
  }

  deleteSingleChoiceAns(control, index) {
    control.removeAt(index)
  }

  setSingleQuestionnaire() {
    let control = <FormArray>this.singleSelectForm.controls.singleSelectQuestions;
    if(this.isEdit){
      control.removeAt(0);
    }
    console.log("sq array -- ", control);
    this.questionnairedata.singleSelectQuestions.forEach(x => {
      control.push(this.fb.group({ 
        question: [x.question, Validators.required],
        answers: this.setSingleChoiceAns(x),
        rating: x.rating,
        questionId: x.questionId
      }))
    })
  }

  setSingleChoiceAns(x) {
    let arr = new FormArray([])
    x.answers.forEach(y => {
      arr.push(this.fb.group({ 
        option: [y.option, Validators.required],
        optionId: y.optionId 
      }))
    })
    return arr;
  }

  showMultipleChoiceQnr(){
    console.log(111);
    this.qnrBtns = false;
    this.qnrFormData = true;
    this.multipleSelectQnr = true;
    if(this.isEdit && this.ucDetail.multipleSelectQuestions){
      console.log(this.qnrMIndex);
      this.qnrMIndex = 1;
    }
    if (this.qnrMIndex>0){
      console.log(this.qnrMIndex);
    let control = <FormArray>this.multiSelectForm.controls.multipleSelectQuestions;
    control.push(
      this.fb.group({
        question: ['', Validators.required],
        answers: this.fb.array([]),
        rating: [''],
        questionId:''
      })
    )
    }
    this.qnrMIndex = this.qnrMIndex+1;
  }

  deleteMultipleChoiceQnr(index) {
    let control = <FormArray>this.multiSelectForm.controls.multipleSelectQuestions;
    control.removeAt(index)
  }

  addNewMultipleChoiceAns(control) {
    control.push(
      this.fb.group({
        option: ['', Validators.required],
        optionId: ''
      }))
  }

  deleteMultipleChoiceAns(control, index) {
    control.removeAt(index)
  }

  setMutipleeQuestionnaire(){
    let control = <FormArray>this.multiSelectForm.controls.multipleSelectQuestions;
    if(this.isEdit){
      control.removeAt(0);
    }
    console.log("mq array", control);
    this.questionnairemultiSelectdata.multipleSelectQuestions.forEach(x => {
      control.push(this.fb.group({ 
        question: [x.question, Validators.required],
        answers: this.setMultipleChoiceAns(x),
        rating: x.rating,
        questionId: x.questionId
       }))
    })
  }
  setMultipleChoiceAns(x) {
    let arr = new FormArray([])
    x.answers.forEach(y => {
      arr.push(this.fb.group({ 
        option: [y.option, Validators.required],
        optionId: y.optionId
      }))
    })
    return arr;
  }

  setCustomQuestionnaire(){
    let control = <FormArray>this.customQnrForm.controls.customQuestions;
    if(this.isEdit){
      control.removeAt(0);
    }
    console.log("Cust Que Arr --", control);
    this.questionnaireCustomdata.customQuestions.forEach(x => {
      control.push(this.fb.group({ 
        question: [x.question, Validators.required],
        questionId: x.questionId,
        rating: x.rating,
        answers: x.answers
      }))
    })
  }

  showCustomQnr(){
    this.qnrBtns = false;
    this.qnrFormData = true;
    this.customQnrBlock = true;
    if(this.isEdit && this.ucDetail.customQuestions){
      this.qnrRIndex = 1;
    }
    if (this.qnrRIndex>0){
      let control = <FormArray>this.customQnrForm.controls.customQuestions;
      control.push(
        this.fb.group({
          question: ['', Validators.required],
          questionId: '',
          rating: '',
          answers: this.fb.array([]),
        })
      )
      }
      this.qnrRIndex = this.qnrRIndex+1;
  }

  deleteCustomQnr(index){
    let control = <FormArray>this.customQnrForm.controls.customQuestions;
    control.removeAt(index)
  }

  hideAddBtns(){
    this.qnrBtns = false;
  }
}

interface Skilltrackdetails {
  pgSkillTrackDtlsList: {
  skillTrackDtlsId: number,
  pgSkillTrackMstr: {
      skillTrackMstrId: number,
      skillTrackName: string
  }
  skillTrackDtlsName: string
}
}

interface Explevel {
    id: number,
    level : string
  }