import {
  AfterViewInit, Component, OnInit, ComponentFactoryResolver
} from '@angular/core';
import {Location} from '@angular/common';
import {BaseComponent} from '../../../share/base.component';
import {Baseconst} from '../../../share/base.constants';
import {NavigationExtras, ActivatedRoute, Router} from '@angular/router';
import {MdDialog, MdSnackBar} from '@angular/material';
import {MediaService} from '../../media/_services/media.service';
import {Photo} from '../../media/_model/photo';
import {TestPlayerService} from '../_services/testPlayer.service';
import {Question, TransitionType} from '../../../models/question';
import {Test} from '../../../models/test';
import {SComponent, SSlide, SComp, SlideComponent, SlideType, SCompType, TestResult, QuestionResult} from '../../../models/component';
import {ResizeEvent} from 'angular-resizable-element';
import {UserInfoComponent} from '../_controller/userInfo.component';
import { FileUploader } from 'ng2-file-upload';
import { UploadsDialogComponent } from '../_controller/uploadsDialog.component';
import { forEach } from '@angular/router/src/utils/collection';

declare var jQuery: any;

@Component({
  selector: 'app-question',
  templateUrl: '../_views/testPlayer.component.html',
  styleUrls: ['../_views/testPlayer.component.scss', '../../../share/e-home.scss']
})
export class TestPlayerComponent extends BaseComponent implements OnInit, AfterViewInit {
  hieghtQuestion: string;
  heightQuestionCenter: string;
  heightQuestionCenterContent: string;
  heightContentTab: string;
  widthQuestionCenter: string;
  medias: Array<Photo>;
  selectedTab: string;
  allMedias: Array<Photo>;
  mediaLoading: boolean;
  testId: string;
  test: Test;
  questions: Array<Question>;
  questionLoading: boolean;
  components: Array<Array<SComponent>>;
  currentSlideId: string;
  currentSlideIndex: number;
  currentSlide: SSlide;
  currentQuestionId: string;
  currentQuestion: Question;
  currentQuestionIndex: number;
  timer: any;
  result: TestResult;
  resultQuestion: QuestionResult;
  canChange: boolean;
  backgroundColor: string;
  currentSlideName: string;
  preview: boolean;
  stimulusOrderInTest: number;
  stimulusOrderInBlock: number;
  currentBlock: string;
  toc: any;
  dialogUploadsResult: any;
  currentUploadCmp: any;
  percentuali: Array<any>;
  topic: any;

  private uploader: FileUploader = new FileUploader({ url: Baseconst.getCompleteBaseUrl() });
  private hasBaseDropZoneOver: boolean = false;

  constructor(protected router: Router,
              public mdSnackBar: MdSnackBar,
              private route: ActivatedRoute,
              private mediaService: MediaService,
              private testPlayerService: TestPlayerService,
              private location: Location,
              public dialog: MdDialog) {
    super(router, mdSnackBar);
    this.height = (window.innerHeight);
    this.width = (window.innerWidth);
    let v = this.width - 470; //right = 200; left=250; margin centrale 10+10;
    let h = this.height;
    if ((this.width - 470) < ((this.height-110) * 1.77)) {
      v = this.width - 470;
      h = v / 1.77;
    } else {
      v = (this.height-110) * 1.77;
    }
    this.hieghtQuestion = (h - 100) + 'px';
    this.heightContentTab = (h - 150) + 'px';
    this.heightQuestionCenter = (h + 30) + 'px';
    this.heightQuestionCenterContent = (h) + 'px';
    this.widthQuestionCenter = '' + v + 'px';
    this.components = new Array();
    this.result = new TestResult();
    this.canChange = false;
    this.currentQuestionIndex = -1;
    this.currentSlideIndex = -1;
    this.currentSlideName = '';
    this.backgroundColor = '#fff';
    this.preview = true;
    this.stimulusOrderInTest = 0;
    this.stimulusOrderInBlock = 0;
    this.currentBlock = null;
    this.toc = new Array();
    this.percentuali = new Array();
  }

  ngOnInit(): void {
    this.allMedias = new Array();
    this.initTest();
    //this.initInputDefault();
    //this.loadMedias().then(() => {
      this.loadTestInfo();
      this.initUploader();
    //});
  }

  initTest() {
    this.test = new Test();
    this.test.options = new Object();
    this.test.questions = new Array<Question>();
    let q = new Question();
    q.slides = new Array<SSlide>();
    this.currentQuestion = q;
    this.currentSlide = new SSlide();
  }

  initUploader() {
    this.route.queryParams.subscribe(params => {
      let token: string = localStorage.getItem('token');
      let URL = Baseconst.getCompleteBaseUrl() + 'atlas/media';

      this.uploader = new FileUploader({ url: URL, autoUpload: true, 
        additionalParameter: {'mediaTestId': params.id}});
      this.uploader.setOptions({ headers: [{ name: 'authtoken', value: token }] });

      // this.uploader.onAfterAddingFile = (fileItem) => {
      //   this.uploadsChange(this.currentUploadCmp, fileItem._file.name);
      // };

      this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
        let buffer = JSON.parse(response)
        if (buffer.status == "OK") {
          this.uploadsChange(this.currentUploadCmp, item, buffer);
          this.openSnackBar('Upload successful!');
        }
        else
          this.openSnackBar('Upload error!');
      };
  });
  }

  isInCheckedString(comp: any, i: number, j: number) {
    
        if (this.resultQuestion.directAnswer[comp.groupName] === undefined ||
          this.resultQuestion.directAnswer[comp.groupName] === null) {
          this.resultQuestion.directAnswer[comp.groupName] = {};
        }
        if (this.resultQuestion.directAnswer[comp.groupName][comp.id] === undefined ||
          this.resultQuestion.directAnswer[comp.groupName][comp.id] === null) {
          this.resultQuestion.directAnswer[comp.groupName][comp.id] = { value: "" };
        }
        let currentCheckedString = this.resultQuestion.directAnswer[comp.groupName][comp.id].value;
        let token = '#' + i + '-' + j
        if (this.resultQuestion.directAnswer[comp.groupName][comp.id].value.indexOf(token) > 0)
          return true
        else
          return false
      }
      onFileOver(cmp: any) {
        this.currentUploadCmp = cmp;
      }
      openDialogUploads(cmp: any) {
        this.currentUploadCmp = cmp;
        let dialogRef = this.dialog.open(UploadsDialogComponent, {
          data: this.uploader
        });
        dialogRef.afterClosed().subscribe(result => {
          this.uploader = result;
        });
      }
  loadTestInfo() {
    this.route.queryParams.subscribe(params => {
      if(params.preview !== undefined && params.preview !== null && params.preview === 'false') {
        this.preview = false;
      }
      this.testPlayerService.requetGetTest(params.id).subscribe(res => {
        if (res.status === 'OK') {
          this.test = res.response;
          //this.initSlides();
          this.loadMedia().then(() => {
            //this.randomizeQuestions();
            this.questions = this.test.questions;
            this.generateToc();
            this.calculatePercentuali();
            if(this.preview) {
              this.startTest();
            } else {
              this.loadUserInfoForm();
            }
          });
          console.log(this.test);
        } else {
          this.processStatusError(res.errors);
          console.error('Server error');
        }
      });
    });
  }

  generateToc() {
    let currentLevel = 0;
    let levels = new Array();

    levels[1] = -1;
    levels[2] = -1;
    levels[3] = -1;

    for (let i = 0; i < this.questions.length; i++) {
      let q = this.questions[i];
        if(q == undefined || q == null) {
          continue;
        }
        if (q.options == undefined || q.options == null) {
          q.options = {};
        }
        if (q.options.level == undefined || q.options.level == null) {
          q.options.level = 1;
        }

        if(q.options.level>1 && levels[1] == -1) {
          let el = {childs:[]};
          this.insertInToc(1, el, currentLevel, levels, this.toc);
        }

        // devo inserire al livello N;
        let element = {
          qid : q.questionId,
          name : q.name,
          childs: []
        };
        this.insertInToc(q.options.level, element, currentLevel, levels, this.toc);
    }
    console.log(this.toc);
  }

  getPercentuale(){
    return this.percentuali[this.currentSlideId];
  }

  calculatePercentuali(){
    let total = 0;
    for (let i = 0; i < this.questions.length; i++) {
      total += this.questions[i].slides.length;
    }
    let ind = 0;
    for (let i = 0; i < this.questions.length; i++) {
      for (let y = 0; y < this.questions[i].slides.length; y++) {
        ind++;
        this.percentuali[this.questions[i].slides[y].slideId] = Math.round((ind/total)*100);
      }
    }

    console.log(this.percentuali);
  }

  insertInToc(level, element, currentLevel, levels, toc){
    if(level == 1){
      element.flqid = element.qid;
      levels[1]++;
      toc[levels[1]] = element;
      if(currentLevel > 1) {
        levels[2] = -1;
        levels[3] = -1;
      }
      currentLevel = level;
    }

    if(level == 2){
      element.flqid = toc[levels[1]].qid;
      levels[2]++;
      toc[levels[1]].childs[levels[2]] = element;
      if(currentLevel > 2) {
        levels[3] = -1;
      }
      currentLevel = level;
    }

    if(level == 3){
      element.flqid = toc[levels[1]].qid;
      levels[3]++;
      toc[levels[1]].childs[levels[2]].childs[levels[3]] = element;
      currentLevel = level;
    }
  }

  startTest() {
    if (this.questions.length > 0) {
      this.startTestCounter();
      this.selectQuestion(this.questions[0]);
      this.currentQuestionIndex = 0;
    }
  }

  loadUserInfoForm() {
    const obj: any = Object.assign({});
    const dialogRef = this.dialog.open(UserInfoComponent, {disableClose: true, data: obj});
    dialogRef.afterClosed().subscribe(res => {
      if (res.status === 'OK') {
        const d = res.data;
        //console.log(d);
        this.result.userInfo = d;
        console.log(this.result);
        this.startTest();
      }
    });
  }

  loadMedia() {
    var promise = new Promise((resolve, reject) => {
      if(this.test !== undefined && this.test !== null){
        /*for(let q of this.test.questions){
          this.loadMediaQuestion(q);
        }*/
        this.mediaService.getMediaByTestId(this.test.TestId).subscribe(res => {
          if (res.status === 'OK') {
            //this.medias = res.response;
            this.allMedias = res.response;
            console.log(this.allMedias);
          } else {
            console.log('Server error');
            this.processStatusError(res.errors);
          }
          resolve();
        })
      } else {
        resolve();
      }
    });
    return promise;
  }

  randomizeQuestions(){
    if(this.test.options !== undefined && this.test.options !== null &&
    (this.test.options.randomized === true || this.test.options.randomized === 'true')) {
      /*TODO effettuare la randomizzazione delle domande;*/
      //prima di tutto devo individuare i diversi gruppi;
      let groups = new Array<Object>();
      for (let i = 0; i < this.test.questions.length; i++) {
        let q = this.test.questions[i];
        let rb = '_default_';
        if(q.options !== undefined && q.options !== null) {
          if(q.options.randomizationBlock !== undefined && q.options.randomizationBlock !== null &&
            q.options.randomizationBlock !== ''){
              rb = q.options.randomizationBlock;
            }
        }
        if (groups[rb] === undefined || groups[rb] === null) {
          groups[rb] = new Array<Question>();
        }
        groups[rb].push(this.test.questions[i]);
      }
      groups =  this.shuffle(groups);
      this.questions = [];
      for(let y = 0; y < groups.length; y++) {
        for(let k = 0; k < groups[y]['questions'].length; k++){
          let q = groups[y]['questions'][k];
          q.groupIndex = (y+1);
          q.questionIndexGroup = (k+1);
          q.groupName = groups[y]['groupName'];
          this.questions.push(q);
        }
      }
      /*let keys = Object.keys(groups);
      this.questions = [];
      for(let y = 0; y < keys.length; y++) {
        for(let k = 0; k < groups[keys[y]].length; k++){
          let q = groups[keys[y]][k];
          q.groupIndex = (y+1);
          q.groupName = keys[y];
          this.questions.push(q);
        }
      }*/
      console.log(this.questions);
    } else {
      this.questions = this.test.questions;
    }
  }

  shuffle(arr) {
    let keys = Object.keys(arr);
    let array = [];
    for (let i = 0; i < keys.length; i++) {
      array[i] = keys[i];
    }
    var currentIndex = keys.length, temporaryValue, randomIndex;
    // While there remain elements to shuffle...
    while (0 !== currentIndex) {
      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    let ret = [];
    for(let i = 0; i < array.length; i++) {
      ret[i] = {'groupName' : array[i], 'questions' : arr[array[i]]};
    }
    return ret;
  }

  selectQuestion(q: Question) {
    if ( q === undefined && q === null){
      this.currentQuestionIndex = 0;
      this.currentQuestion = this.questions[0];
      this.currentQuestionId = this.currentQuestion.questionId;
    } else {
      this.currentQuestion = q;
      this.currentQuestionId = q.questionId;
      this.currentQuestionIndex = this.getCurrentQuestionIndex();
    }
    if(this.currentBlock !== q.groupName){
      this.currentBlock = q.groupName;
      this.stimulusOrderInBlock = 0;
    }
    
    this.startQuestionCounter();
    this.initSlides(this.currentQuestion);
    this.selectFirstSlide(this.currentQuestion);
  }

  selectFirstSlide(q: Question){
    if ( q !== undefined && q !== null){
      if(q.slides !== undefined && q.slides !== null && q.slides.length > 0) {
        this.currentSlideIndex = -1;
        this.goToNextSlide();
        //this.selectSlide(q.slides[0]);
      }
    }
  }
  /*selectSlide(s: SSlide){
    if ( s !== undefined && s !== null) {
      this.currentSlide = s;
      this.currentSlideId = s.slideId;
      this.setSlideConfig();
    }
    this.completeSlideChange();
  }*/

  completeSlideChange() {
    clearTimeout(this.timer);
    this.timer = null;
    this.startSlideCounter();
    this.checkSlideAction();
  }

  setSlideConfig(){
    if (this.currentSlide.options !== undefined && this.currentSlide.options !== null &&
      this.currentSlide.options.color !== undefined && this.currentSlide.options.color !== null) {
        this.backgroundColor = this.currentSlide.options.color;
    } else {
      this.backgroundColor = '#fff';
    }
    if (this.currentSlide.options !== undefined && this.currentSlide.options !== null &&
      this.currentSlide.options.name !== undefined && this.currentSlide.options.name !== null) {
        this.currentSlideName = this.currentSlide.options.name;
    } else {
      this.currentSlideName = '';
    }
  }

  changeSlide(i: number) {
    /*if (!this.canChange) {
      return;
    }*/
    if (i < this.currentQuestion.slides.length) {
      this.currentSlide = this.currentQuestion.slides[i];
      this.currentSlideIndex = i;
      this.currentSlideId = this.currentSlide.slideId;
      this.setSlideConfig();
    }
    this.completeSlideChange();
  }

  initSlides(question : Question) {
    if(question.slides==undefined || question.slides == null){
      question.slides = new Array();
    }
    for ( let i = 0; i < question.slides.length; i++) {
      this.components[question.slides[i].slideId] = this.convertComponents(question.slides[i]);
    }
    setTimeout(() => {
      this.bindTopicClick();
    }, 100);
  }

  convertComponents(slide){
    if( slide == undefined || slide == null ||
      slide.slideContent == undefined || slide.slideContent == null ||
      slide.slideContent.componentArray == undefined || slide.slideContent.componentArray == null){
        return new Array<SComponent>();
      }
    let ret = new Array<SComponent>();
    let sw = jQuery('#s-content').innerWidth();
    let sh = jQuery('#s-content').innerHeight();
    for(let i = 0; i < slide.slideContent.componentArray.length; i++){
      let comp = new SComponent();
      comp.fromSComp(slide.slideContent.componentArray[i], sw, sh);
      slide.slideContent.componentArray[i].id = comp.id;
      if(comp.mediaId != undefined && comp.mediaId != null && comp.mediaId.trim() != ''){
        comp.url = this.getMediaUrlFromId(comp.componentType, comp.mediaId);
        if(comp.componentType === SCompType.VIDEO) {
          let media = this.getMediaFromId(comp.componentType, comp.mediaId);
          //comp.url = 'http://testing01.eclettica.net:9000/retrievePublic?code=' + media.publicUrl;
          comp.url = Baseconst.protocol + '://' + Baseconst.url +'/retrievePublic?code=' + media.publicUrl;
       }
      }
      if(comp.options.topics != undefined && comp.options.topics != null &&
        comp.options.topics.trim() != ""){
          try{
            comp.options.topicsObj = JSON.parse(comp.options.topics);
            console.log(comp.options.topicsObj);
          } catch(exc){
            console.log(exc);
          }
        }
      ret.push(comp);
    }
    
    return ret;
  }

  private getMediaUrlFromId(type, mediaId){
    //TODO qui è necessario effettuare la ricerca del media;
    if(mediaId == undefined || mediaId == null) {
      return null;
    }
    for ( let media of this.allMedias){
      if ( media.mediaId === mediaId) {
        return media.mediaPath;
      }
    }
    console.log(type + ' ' + mediaId);
    return '';
  }

  private getMediaFromId(type, mediaId){
    //TODO qui è necessario effettuare la ricerca del media;
    if(mediaId == undefined || mediaId == null) {
      return null;
    }
    for ( let media of this.allMedias){
      if ( media.mediaId === mediaId) {
        return media;
      }
    }
    console.log(type + ' ' + mediaId);
    return null;
  }


  getCurrentSlide(){
    const question = this.getCurrentQuestion();
    for ( let i = 0; i < question.slides.length; i++) {
      if ( question.slides[i].slideId === this.currentSlideId) {
        return question.slides[i];
      }
    }
  }

  getCurrentQuestion(){
    for ( let y = 0; y < this.questions.length; y++) {
      if ( this.questions[y].questionId === this.currentQuestionId){
        return this.questions[y];
      }
    }
    return null;
  }

  getCurrentQuestionIndex(){
    for ( let y = 0; y < this.questions.length; y++) {
      if ( this.questions[y].questionId === this.currentQuestionId){
        return y;
      }
    }
    return null;
  }


  backQuestion() {
    clearTimeout(this.timer);
    this.timer = null;
    const navigationExtras: NavigationExtras = {
      queryParams: {
        id: this.test.TestId
      }
    };
    this.router.navigate(['/home/atlas/testedit'], navigationExtras);
  }


  ngAfterViewInit() {
    // this.initDragDropComponent();
    // jQuery('#drag-component').draggable();
      //this.bindTopicClick();
  }

  bindTopicClick(){
    jQuery('fra').click((event) => {
      console.log(this);
      console.log(event.currentTarget.getAttribute('tid'));
      let tid = event.currentTarget.getAttribute('tid');
      let components = this.components[this.currentSlideId];
      components.forEach(element => {
        if(element.options == undefined || element.options == null ||
          element.options.topicsObj == undefined || element.options.topicsObj == null) {
            return;
          }
          if(element.options.topicsObj[tid] == undefined || element.options.topicsObj[tid] == null)
            return;
            let topic = element.options.topicsObj[tid];
            this.showTopic(topic);
      });
    }
    );
  }

  showTopic(topic){
    console.log(topic);
    this.topic = topic;
  }

  hideTopic(){
    this.topic = null;
  }

  checkTransition(c: SComponent, $event){
    if (c === undefined || c === null 
      || c.componentType === undefined || c.componentType === null
      || c.options === undefined || c.options === null) {
      return;
    }
    switch (c.componentType) {
      case SCompType.TEXT:
      case SCompType.TEXTAREA:
        this.checkTransitionText(c, $event);
        break;
        case SCompType.RADIO:
        case SCompType.CHECKBOX:
        case SCompType.CLICK_AREA:
        case SCompType.BUTTON:
        case SCompType.IMAGE:
        case SCompType.UPLOADS:
        case SCompType.CHECKABLETABLE:
        this.checkTransitionCheckbox(c, $event);
        break;
      default:
        break;
    }
  }

  checkTransitionText(c: SComponent, $event) {
    if (c === undefined || c === null 
      || c.componentType === undefined || c.componentType === null
      || c.options === undefined || c.options === null) {
      return;
    }
    if($event.key != "Enter") {
      return;
    }
    if(c.transition === undefined || c.transition === null) {
      return;
    }
    if (c.transition == true) {
      this.performTransition();
    }
  }

  checkTransitionCheckbox(c: SComponent, $event) {
    if (c === undefined || c === null 
      || c.componentType === undefined || c.componentType === null
      || c.options === undefined || c.options === null) {
      return;
    }
    if(c.transition === undefined || c.transition === null) {
      return;
    }
    if (c.transition === true) {
      this.performTransition();
    }
  }

  performTransition() {
    this.stopSlideCounter();
    clearTimeout(this.timer);
    this.timer = null;
    if (this.currentSlideIndex !== undefined && this.currentSlideIndex !== null) {
      this.goToNextSlide();
    } else {
      //si deve gestire il caso in cui, per qualche motivo, non viene incrementato l'indice;
    }
    
  }

  goToNextSlide() {
    if (this.currentSlideIndex < (this.currentQuestion.slides.length - 1)) {
      //ci sono altre slides
      this.changeSlide(this.currentSlideIndex + 1);
      /*this.currentSlideIndex++;
      this.currentSlide = this.currentQuestion.slides[this.currentSlideIndex];
      this.currentSlideId = this.currentSlide.slideId;
      this.setSlideConfig();
      this.checkSlideAction();*/
    } else {
      this.stopQuestionCounter();
      this.goToNextQuestion();
    }
  }

  goToNextQuestion() {
    if (this.currentQuestionIndex === undefined && this.currentQuestionIndex === null) {
      this.currentQuestionIndex = -1;
    }
    if (this.currentQuestionIndex < (this.questions.length - 1)) {
      this.selectQuestion(this.questions[this.currentQuestionIndex + 1]);
      /*this.currentQuestionIndex++;
      this.currentQuestion = this.questions[this.currentQuestionIndex];
      this.currentQuestionId = this.currentQuestion.questionId;
      this.initSlides(this.currentQuestion);
      this.selectFirstSlide(this.currentQuestion);*/
    } else {
      this.stopTestCounter();
      this.testPlayerService.requestCreateReport(this.result).subscribe(res => {
        console.log(res);
        if (res.status === 'OK') {
          this.test = res.response;
        } else {
          this.processStatusError(res.errors);
          console.error('Server error');
        }
      });
      console.log('TEST ENDED');
      this.openSnackBar('TEST ENDED!!!');         
    }

  }

  checkSlideAction() {
    if(this.currentSlide.transitionType !== undefined && this.currentSlide.transitionType !== null){
      for(let t of this.currentSlide.transitionType){
        if(t == TransitionType.time &&
          this.currentSlide.options !== undefined && this.currentSlide.options !== null &&
        this.currentSlide.options.seconds !== undefined && this.currentSlide.options.seconds !== null &&
        this.currentSlide.options.seconds > 0){
          const millisec = this.currentSlide.options.seconds * 1000;
          this.timer = setTimeout(() => {
            this.performTransition();
          }, millisec);
        }
      }
    }
  }

  onPlayerReady($event, cid) {
    console.log($event);
    $event.play();
  }

  startTestCounter(){
    this.result.testId = this.test.TestId;
    this.result.testName = this.test.TestName;
    this.result.piId = ''; // TODO inserire l'id utente
    this.result.questions = new Array<QuestionResult>();
    this.result.testStartTime = (new Date()).getTime();
    console.log('start test: ' + (new Date()).getTime());
  }
  startQuestionCounter(){
    this.resultQuestion = new QuestionResult();
    this.resultQuestion.directAnswer = {};
    this.resultQuestion.expectedAnswer = {};
    
    this.resultQuestion.randomizationBlock = this.currentQuestion.groupName;
    this.resultQuestion.randomizationPresentationBlock = '' + this.currentQuestion.questionIndexGroup;
    console.log('start question: ' + (new Date()).getTime());
  }
  startSlideCounter() {
    console.log('start slide: ' + (new Date()).getTime());
    if (this.currentSlide.type === SlideType.STIMULUS) {
      this.stimulusOrderInBlock++;
      this.stimulusOrderInTest++;
      this.resultQuestion.stimulusSlideId = this.currentSlide.slideId;
      this.resultQuestion.stimulusSlideNumber = this.currentSlideIndex;
      this.resultQuestion.stimulusOrderInBlock = this.stimulusOrderInBlock;
      this.resultQuestion.stimulusOrderInTest = this.stimulusOrderInTest;
      this.resultQuestion.stimulusStartTime = (new Date()).getTime();
    }
    if (this.currentSlide.type === SlideType.ANSWER) {
      this.resultQuestion.answerStartTime = (new Date()).getTime();
    }
  }
  stopTestCounter(){
    this.result.testEndTime = (new Date()).getTime();
    console.log('stop test: ' + (new Date()).getTime());
    console.log(this.result);
  }
  stopQuestionCounter(){
    this.result.questions.push(this.resultQuestion);
    console.log('stop question: ' + (new Date()).getTime());
  }
  stopSlideCounter(){
    if (this.currentSlide.type === SlideType.STIMULUS) {
      this.resultQuestion.stimulusEndTime = (new Date()).getTime();
    }
    if (this.currentSlide.type === SlideType.ANSWER) {
      this.resultQuestion.expectedAnswer = this.getExpectedAnswer();
      this.getCurrentAnswer();
      this.resultQuestion.answerEndTime = (new Date()).getTime();
    }
    console.log('stop slide: ' + (new Date()).getTime());
  }

  getExpectedAnswer(): any {
    let ret = {};
    for (let i = 0; i < this.currentSlide.slideContent.componentArray.length; i++) {
      let c = this.currentSlide.slideContent.componentArray[i];
      if (c.componentType === SCompType.RADIO) {
        for (let y = 0; y <c.options.numRadio; y++) {
          if(c.options['radioComponentIsCorrect_'+y] === 'true'){
            ret[c.options.groupName] = {};
            ret[c.options.groupName].label = c.options['radioComponentLabel_'+y];
            ret[c.options.groupName].value = c.options['radioComponentValue_'+y];
          }
        }
      }
      if(c.options) {
        if(c.options.isCorrect === 'true') {
          let n = '';
          if(c.options.groupName !== undefined && c.options.groupName !== null) {
            n = c.options.groupName;
          }
          if(c.options.name !== undefined && c.options.name !== null) {
            n = c.options.name;
          }
          if (c['name'] !== undefined && c['name'] !== null) {
            n = c['name'];
          }
          ret[n] = {};
          if(c.options.label !== undefined && c.options.label !== null) {
            ret[n].label = c.options.label;
          } else {
            ret[n].label = n;
          }
          ret[n].value = c.options.value;
        }
      }
      if (c.componentType === SCompType.CHECKABLETABLE) {
        ret[c.options.groupName] = {};
        ret[c.options.groupName].checkedString = c.options['checkedString'];
        ret[c.options.groupName].value = c.options['checkedString'];
      }

    }

    return ret;
  }
  getCurrentAnswer(){
    this.currentSlide.slideContent.componentArray.forEach(comp => {
      switch (comp.componentType) {
        case SCompType.TEXT:
        case SCompType.TEXTAREA:
          this.textChange(comp);
          break;
      case SCompType.CHECKBOX:
          break;
      case SCompType.RADIO:
          break;
      case SCompType.IMAGE:
          //this.imageChange(comp);
          break;
      case SCompType.CLICK_AREA:
          //this.clickareaChange(comp);
          break;
      case SCompType.RANGE:
          this.rangeChange(comp);
          break;
        default:
          break;
      }

    });
  }

  textChange(c) {
    let t = jQuery('#' + c.id).val();
    console.log("value: " + t);
    this.resultQuestion.directAnswer[c.options.name] = {};
    this.resultQuestion.directAnswer[c.options.name].value = t;
  }

  textAreaChange(c){

  }

  checkboxChange(comp){
    if(this.resultQuestion.directAnswer[comp.groupName] === undefined ||
      this.resultQuestion.directAnswer[comp.groupName] === null){
        this.resultQuestion.directAnswer[comp.groupName] = {};
      }
      if (this.resultQuestion.directAnswer[comp.groupName][comp.id] === undefined ||
        this.resultQuestion.directAnswer[comp.groupName][comp.id] === null) {
          this.resultQuestion.directAnswer[comp.groupName][comp.id] = {isChecked:false};
        }
        if(this.resultQuestion.directAnswer[comp.groupName][comp.id].isChecked === false){
          this.resultQuestion.directAnswer[comp.groupName][comp.id].isChecked = true;
          this.resultQuestion.directAnswer[comp.groupName][comp.id].value = comp.value;
        } else {
          this.resultQuestion.directAnswer[comp.groupName][comp.id].isChecked = false;
          this.resultQuestion.directAnswer[comp.groupName][comp.id].value = null;
        }
  }
  radioChange(comp, elem){
    if(this.resultQuestion.directAnswer[comp.groupName] === undefined ||
      this.resultQuestion.directAnswer[comp.groupName] === null){
        this.resultQuestion.directAnswer[comp.groupName] = {};
      }
    if (this.resultQuestion.directAnswer[comp.groupName][comp.id] === undefined ||
      this.resultQuestion.directAnswer[comp.groupName][comp.id] === null) {
        this.resultQuestion.directAnswer[comp.groupName][comp.id] = {isSelected:false};
      }
      this.resultQuestion.directAnswer[comp.groupName][comp.id].isSelected = true;
      this.resultQuestion.directAnswer[comp.groupName][comp.id].value = elem.value;
    
  }
  uploadsChange(comp, fileItem, response) {
    if (this.resultQuestion.directAnswer['uploads'] === undefined ||
      this.resultQuestion.directAnswer['uploads'] === null) {
      this.resultQuestion.directAnswer['uploads'] = {};
    }
    if (this.resultQuestion.directAnswer['uploads'][comp.id] === undefined ||
      this.resultQuestion.directAnswer['uploads'][comp.id] === null) {
      this.resultQuestion.directAnswer['uploads'][comp.id] = [];
    }

    let json = { id: response.response.mediaId, filename: fileItem._file.name };
    this.resultQuestion.directAnswer['uploads'][comp.id].push(json);

  }

  checkableTableChange(comp, i, j) {
    if (this.resultQuestion.directAnswer[comp.groupName] === undefined ||
      this.resultQuestion.directAnswer[comp.groupName] === null) {
      this.resultQuestion.directAnswer[comp.groupName] = {};
    }
    if (this.resultQuestion.directAnswer[comp.groupName][comp.id] === undefined ||
      this.resultQuestion.directAnswer[comp.groupName][comp.id] === null) {
    }

    let currentCheckedString = this.resultQuestion.directAnswer[comp.groupName][comp.id].value;
    let token = '#' + i + '-' + j

    if (currentCheckedString.indexOf(token) === -1)
      currentCheckedString = currentCheckedString + token
    else
      currentCheckedString = currentCheckedString.replace(token, '');

    this.resultQuestion.directAnswer[comp.groupName][comp.id].value = currentCheckedString;

  }
  imageChange(comp){
    if (comp.options.checkable !== 'true' && comp.options.checkable !== true) {
      return;
    }
    if (this.resultQuestion.directAnswer[comp.name] === undefined ||
      this.resultQuestion.directAnswer[comp.name] === null){
        this.resultQuestion.directAnswer[comp.name] = {};
        this.resultQuestion.directAnswer[comp.name].name = comp.name;
      }
      if (this.resultQuestion.directAnswer[comp.name][comp.id] === undefined ||
        this.resultQuestion.directAnswer[comp.name][comp.id] === null) {
        this.resultQuestion.directAnswer[comp.name][comp.id] = {isChecked:false};
      }
      if(this.resultQuestion.directAnswer[comp.name][comp.id].isChecked === false){
        comp.options.isChecked = true;
        this.resultQuestion.directAnswer[comp.name][comp.id].isChecked = true;
        this.resultQuestion.directAnswer[comp.name][comp.id].value = comp.value;
      } else {
        comp.options.isChecked = false;
        this.resultQuestion.directAnswer[comp.name][comp.id].isChecked = false;
        this.resultQuestion.directAnswer[comp.name][comp.id].value = null;
      }
  }
  clickareaChange(comp){
  }
  rangeChange(comp){
    let t = jQuery('' + comp.name).val();
    console.log("value: " + t);
    this.resultQuestion.directAnswer[comp.options.name] = {};
    this.resultQuestion.directAnswer[comp.options.name].value = t;
  }


  gotoSection(section){
    //console.log(section);
    let q = null;
    for ( let y = 0; y < this.questions.length; y++) {
      if ( this.questions[y].questionId === section.qid){
        q = this.questions[y];
      }
    }
    if (q != null) {
      this.stopSlideCounter();
      clearTimeout(this.timer);
      this.stopQuestionCounter();
      this.selectQuestion(q);
    }
  }


}
