import { Component, OnInit, HostListener, ViewChild } from '@angular/core';
import { CONFIG } from '../../../app/config';
import { HyperService } from '../../core/services/http.service';
import { LocalStorage } from '../../core/services/local_storage.service';
import { ActivatedRoute } from '@angular/router';
import { Router } from "@angular/router";
import { timer } from 'rxjs/observable/timer';
import { take, map } from 'rxjs/operators';
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/timer";
import "rxjs/add/operator/finally";
import "rxjs/add/operator/takeUntil";
import "rxjs/add/operator/map";
import { Subscription } from "rxjs";
import { TimerObservable } from "rxjs/observable/TimerObservable";
import { Input, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy } from '@angular/core';
import * as moment from 'moment'
import { ScorePopupComponent } from '../score-popup/score-popup.component';

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

  @ViewChild(ScorePopupComponent) content_modal: ScorePopupComponent;

  @HostListener('window:unload', ['$event'])
  unloadHandler(event) {
      return window.confirm('Want to leave the before completing?');

  }



  @HostListener('window:beforeunload', ['$event'])
  beforeUnloadHander(event) {
      return window.confirm('Want to leave the before completing?');
  }

  question: any;
  sub: any;
  id: number = 1;
  active_question: number = 0;
  countDown;
  count = 30;
  countdown: string;
  assessment_detail: any;
  isloaded: boolean = false;
  isActive: any;
  gender: any;
  genders: any;
  user: any;
  error_message: string;
  ans_arr: any = [];
  is_completed: boolean = false;
  counter_min: any = 30;
  counter_sec: any = 0;
  start_time: any;
  end_time: any;
  sendData: any = {};
  review: boolean = false;
  private tick: number;
  private subscription: Subscription;
  is_vaild: boolean = true;
  check_mandatory: any;
  loader_timing: any;
  loader_delay: any;
  fullload: any;
  halfleft: any;
  halfright: any;
  scrollleft_percentage: number = 0;
  with_timer: number;


  constructor(private route: ActivatedRoute, private server: HyperService, private router: Router) {
      let today = Date.now();
      this.start_time = moment(today).format('YYYY-MM-DD hh:mm:ss');
      this.sub = this.route.params.subscribe(params => {
          this.id = params['id'];
      });
      this.route.url.subscribe(url => {
          this.getAssessment()
      });
      this.assessment_detail = LocalStorage.getValue('selected_assessment')
      this.with_timer = this.assessment_detail.assessmenttimetype; 
      LocalStorage.setValue('is_assessment_completed', false)
  }

  ngOnInit() {}

  getAssessment() {
      this.server.get("assessment/question/" + this.id + "")
          .then((data) => {
              if (data.status == 200 && data.result.response != 'failed') {
                  this.question = data.result.data;
                  if (this.with_timer == 1) {
                      this.questionTimeSet(this.assessment_detail.assessmenttime)
                  }
                  for (let i = 0; i < this.question.length; i++) {
                      let data = {
                          "aqid": this.question[i].aqid,
                          "qid": this.question[i].qid,
                          "options": []
                      }
                      this.ans_arr.push(data);
                  }
                  for (let i = 0; i < this.question.length; i++) {
                      this.question[i].is_ans = 0;
                      this.question[i].id = i + 1;
                  }
                  this.isloaded = true; 
              }else if (data.result.status == 406 ) {
                    alert(data.result.message)
              }
               else if (data.result.status == 401 && data.result.response == 'failed') {}
          });
  }


  questionTimeSet(Time) {
      this.loader_timing = Time * 60;
      this.loader_delay = this.loader_timing / 2; 
      const interval = 1000;
      const duration = 10 * 6000 * Time;
      const stream$ = Observable.timer(0, interval)
          .finally(() => this.onsubmit(0))
          .takeUntil(Observable.timer(duration + interval))
          .map(value => duration - value * interval);
      stream$.subscribe(value => this.formatMin(value));
      this.fullload = {
          'animation-duration': this.loader_timing + 's'
      } 
      this.halfleft = {
          'animation-duration': this.loader_delay + 's'
      } 
      this.halfright = {
          'animation-duration': this.loader_delay + 's',
          'animation-delay': this.loader_delay + 's'
      }


  }

  formatMin(s) {
      let ms = s % 1000;
      s = (s - ms) / 1000;
      let secs = s % 60; 
      s = (s - secs) / 60;
      let mins = s % 60;
      let hrs = (s - mins) / 60;
      if (hrs > 0) {
          this.countdown = hrs + ':' + mins + ':' + secs;
      } else {
          if(secs==0){
            this.countdown = mins + ':' +  '00';
          }else{
            this.countdown = mins + ':' + secs;
          }
          
      }

  }



  selectRadio(selected_ans, question_data, qus_index, option_index) { 
      this.question[qus_index].options[option_index].selected = selected_ans.optid;
      //Radio Button
      if (question_data.questiontypeid == 1) {
          //Not answered
          if (this.ans_arr[qus_index].options == null || this.ans_arr[qus_index].options == '' || this.ans_arr[qus_index].options.length == 0) {
              this.ans_arr[qus_index].options.push(selected_ans.optid)
              this.question[qus_index].is_ans = 1;
          }
          //Already answerd
          else {
              this.ans_arr[qus_index].options.splice(0, 1);
              this.ans_arr[qus_index].options.push(selected_ans.optid)
              if (this.ans_arr[qus_index].options == null || this.ans_arr[qus_index].options == '' || this.ans_arr[qus_index].options.length == 0) {
                  this.question[qus_index].is_ans = 0;
              } else {
                  this.question[qus_index].is_ans = 1;
              }
          }

      } 
      if (question_data.questiontypeid == 2) {
          //Not answered
          if (this.ans_arr[qus_index].options.indexOf(selected_ans.optid) > -1) {
              this.ans_arr[qus_index].options.splice(0, 1);
              this.question[qus_index].is_ans = 0;
              // this.ans_arr[qus_index].options = selected_ans.optid
          }
          //Already answerd
          else {
              this.ans_arr[qus_index].options.push(selected_ans.optid)
              this.question[qus_index].is_ans = 1;
          }


      }

  }


  onsubmit(type) {
      if (type == 0) {
          this.postAssessment();
      } else {
          this.check_mandatory = this.question.filter(question => question.is_mandatory == '1' && question.is_ans == 0);
           if (this.check_mandatory.length > 0 || this.check_mandatory != '') {
              this.is_vaild = false;
          } else {
              this.postAssessment();
          }

      }
  }

  postAssessment() {
      this.is_vaild = true;
      let end = Date.now();
      this.end_time = moment(end).format('YYYY-MM-DD hh:mm:ss');
      this.server.post("assessment/" + this.id, {
              ans_arr: JSON.stringify(this.ans_arr),
              startdatetime: this.start_time,
              enddatetime: this.end_time
          })
          .then((data) => {
              if (data.status == 200 && data.result.response == "success") {
                  this.sendData = data;
                  this.sendData.result_id = data.result.data.result_id;
                  this.sendData.assessment_id = this.id;
                  LocalStorage.setValue('is_assessment_completed', true)
                  this.content_modal.showcontentrModal('Result', this.sendData, (data) => {
                      this.is_completed = true;
                      this.onreview();
                  })
              } else if (data.result.response == "failed") {} else if (data.status == 500) {} else {
                  alert("Please check your internet connection");
              }
          })
  }

  onreview() {
      this.review = true;
      this.server.get("assessment/review/" + this.sendData.result_id)
          .then((data) => {
              if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                  this.question = data.result.data;
                  this.isloaded = true;
                  this.selectQuestion(0)
              } else if (data.result.status == 401 && data.result.response == 'failed') {
                  this.router.navigateByUrl('');
              } else if (data.result.status == 406 && data.result.response == 'failed') {
                  this.isloaded = false;
                  this.error_message = data.result.message
              } else {
                  this.question = [];
              }
          });
  }



  selectQuestion(selected_no) {
      this.active_question = selected_no;

  }

  prevQuestion(val) {  
    let pagenation = document.getElementById('page');
    this.scrollleft_percentage -= 50;
    pagenation.scrollLeft = this.scrollleft_percentage;
      this.active_question -= 1;
  }

  nextQuestion(val) { 
    let pagenation = document.getElementById('page');
    this.scrollleft_percentage += 50;
    pagenation.scrollLeft = this.scrollleft_percentage;
      this.active_question += 1;
  }

  onContine() {
    this.is_completed = true;
    this.router.navigateByUrl('myassessment');
}



}