import { Component, OnInit, ViewChild } from '@angular/core';
import { LocalStorage } from '../../core/services/local_storage.service';
import { HyperService } from '../../core/services/http.service';
import { Router, ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import { AddparticipantpopComponent } from '../addparticipantpop/addparticipantpop.component';
import { ConfirmpopComponent } from '../confirmpop/confirmpop.component';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ToasterService } from '@service/toaster.service';
import { Location } from '@angular/common';

import {Subject, Observable} from 'rxjs';
import {WebcamImage, WebcamInitError, WebcamUtil} from 'ngx-webcam';

declare var $:any;

@Component({
  selector: 'app-dsetrainingfeedback',
  templateUrl: './dsetrainingfeedback.component.html',
  styleUrls: ['./dsetrainingfeedback.component.scss']
})
export class DseTrainingFeedbackComponent implements OnInit {
  sub: any;
  loader: boolean;
  @ViewChild(AddparticipantpopComponent) participant_pop: AddparticipantpopComponent;
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  schedule_data: any;
  role_num;
  assessment_id;
  feedback_datas: any;
  feedback_question: any = [];
  trainerfeedbackquestion: any=[];
  trainingfeedbackquestion: any = [];
  anslist: any = [];
  trainingover_score : any = 0;
  trainerover_score : any = 0;
  remark;
  feedback_status: boolean;
  type;
  constructor(private server: HyperService, private _location : Location,private router: Router, private route: ActivatedRoute,public toaster : ToasterService) {
    this.sub = this.route.params.subscribe(params => {
      this.assessment_id = (params['id']);
    });
  }

  ngOnInit() {
    this.role_num = LocalStorage.getValue('user_data').role;
    LocalStorage.setValue('is_firsttime', false);
    this.getdetails();
    let data = LocalStorage.getValue('DSEFeedbackdata');
    this.schedule_data = JSON.parse(data);
    this.schedule_data = this.schedule_data[0];
    this.feedback_status = this.schedule_data.is_completed == 1 ? true : false;
  }

  getdetails(){
    if(this.role_num == 10){
      this.loader = true; 
      this.server.get("crtraining/trainingfeedbackquestion/"+this.assessment_id).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.feedback_datas = data.result.data;
          this.feedback_question = this.feedback_datas.questions;
          this.feedback_question.forEach((question)=>{
            if(question.questiontype == 1){
              this.trainingfeedbackquestion.push(question)
            }else{
              this.trainerfeedbackquestion.push(question)
            }
          });
        } else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }
      })
    }else{
      this.loader = true; 
      this.server.get("crtraining/trainingalluserfeedbackquestion/"+this.assessment_id).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.feedback_datas = data.result.data;
          this.feedback_question = this.feedback_datas.questions;
          this.feedback_question.forEach((question)=>{
            if(question.questiontype == 1){
              this.trainingfeedbackquestion.push(question)
            }else{
              this.trainerfeedbackquestion.push(question)
            }
          });
        } else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }
      })
    }
  }

  
  backclicked(){
    this._location.back();
  }

  oncancel(){
    this.router.navigateByUrl('trainer');
  }
  trainingscore = [];
  trainerscore = [];
  chooseans(e,data){
    let value = [];
    
    value.push(e.target.value)
    let resdata = {
      "qid" : data.qid,
      "aqid" : data.aqid,
      "options" : [e.target.value] 
    }
    if(this.anslist.length!=0){
      let objIndex = this.anslist.findIndex((obj => obj.aqid == data.aqid));
      if(objIndex == -1){
        this.anslist.push(resdata)
      }else{
        this.anslist[objIndex].qid = resdata.qid;
        this.anslist[objIndex].aqid = resdata.aqid;  
        this.anslist[objIndex].options = resdata.options;  
      }
    }else{
      this.anslist.push(resdata);
    }
    // sum and average
    if(data.questiontype == 1){
      if(this.trainingscore.length!=0){
        let objIndex = this.trainingscore.findIndex((obj => obj.aqid == data.aqid));
        if(objIndex == -1){
          this.trainingscore.push(resdata)
        }else{
          this.trainingscore[objIndex].qid = resdata.qid;
          this.trainingscore[objIndex].aqid = resdata.aqid;  
          this.trainingscore[objIndex].options = resdata.options;  
        }
      }else{
        this.trainingscore.push(resdata);
      }
    }else{
      if(this.trainerscore.length!=0){
        let objIndex = this.trainerscore.findIndex((obj => obj.aqid == data.aqid));
        if(objIndex == -1){
          this.trainerscore.push(resdata)
        }else{
          this.trainerscore[objIndex].qid = resdata.qid;
          this.trainerscore[objIndex].aqid = resdata.aqid;  
          this.trainerscore[objIndex].options = resdata.options;  
        }
      }else{
        this.trainerscore.push(resdata);
      }
    }
    if(data.questiontype == 1){
      this.trainingover_score = 0;
      this.trainingscore.forEach((res)=>{
        let val = res.options;
        this.trainingover_score +=Number(val);
      })
    }else {
      this.trainerover_score = 0;
      this.trainerscore.forEach((res)=>{
        let val = res.options;
        this.trainerover_score +=Number(val);
      })
    }
    var a = (this.trainingover_score / this.trainingfeedbackquestion.length).toFixed(1);
    var b = (this.trainerover_score / this.trainerfeedbackquestion.length).toFixed(1);
    $('.training_score').val(a)
    $('.trainer_score').val(b)

    var res1 = this.feedback_question.filter(item1 => this.anslist.some(item2 => (item2.aqid === item1.aqid)))
    res1.forEach((ques)=>{
        $(".optionerr"+ques.aqid).css("display","none")
    });
  }

  onsubmitquestion(){
    var res = this.feedback_question.filter(item1 => !this.anslist.some(item2 => (item2.aqid === item1.aqid)))
    res.forEach((ques)=>{
        $(".optionerr"+ques.aqid).css("display","block")
    });
    if(res.length == 0){
      let senddata = {};
      senddata = {
        "startdatetime" : this.schedule_data.start_date,
        "enddatetime" : this.schedule_data.end_date,
        "ans_arr" : JSON.stringify(this.anslist),
        "remarks" : this.remark
      }
      this.loader = true;
      this.server.post("survey/"+this.assessment_id,senddata).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.anslist = [];
          let msg2 = "Feedback Submitted successfully";
          this.confirm_pop.confirmPopups(msg2, (data) => {
          this.router.navigateByUrl('trainer');
        })
        } else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }
      })
    }
  }

  

}
