import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {
  FormBuilder,
} from '@angular/forms';
import { NgxSpinnerService } from 'ngx-spinner';
import { ServicesService } from '../../services.service';
import { AuthserviceService } from '../../authservice.service';
import { KnowledgeserviceService } from '../../services/knowledge/knowledgeservice.service';
import { SharedDataService } from 'src/app/services/SharedData/shared-data.service';
@Component({
  selector: 'app-knowquestion',
  templateUrl: './knowquestion.component.html',
  styleUrls: ['./knowquestion.component.scss'],
})
export class KnowquestionComponent implements OnInit {
  dislayhidden: any;
  scrWidth: any;
  Knowass = [];
  QuestionDisplay: any;
  NextChnageQuestionNo: number;
  nextQuestionArray = [];
  QuestionLen: number;
  id: any;
  Ass_id: any;
  userid: any;
  AnswerComplter: any;
  name: any;
  correct = 0;
  incorrct = 0;
  ViewBoolean = false;
  newerror = false;
  RowNumber: any;
  Disabled: boolean = false
  RemainquestionImage = false;
  CompleteImage = false;
  constructor(
    public KnowledgeserviceService: KnowledgeserviceService,
    public ActiveRoute: ActivatedRoute,
    public service: ServicesService,
    public auth: AuthserviceService,
    public spinner: NgxSpinnerService,
    public fb: FormBuilder,
    public router: Router,
    public route: ActivatedRoute,
    public sharedDataService: SharedDataService
  ) {
    this.service.title = '';
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }

    this.userid = localStorage.getItem('CisspUserId');
    this.service.headershow = true;
    this.service.SearchValue = false;
    var access = window.localStorage.getItem('accessitem');
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      CATresult: false,
      CATQue: false,
      PracticeResult: false,
      studentprofile: false,
      Practiceques: false,
      knowques: false,
      knowresult: false,
      resource: false,
      liveSupport: false
    };
    if (access) {
      var set = JSON.parse(<string>access);
      if (set) {
        this.service.access.CATaccess = set.CAT_access ? true : false;
        this.service.access.Knowaccess = set.KA_access ? true : false;
        this.service.access.Practiceaccess = set.PT_access ? true : false;
        this.service.access.livechat_access = set.livechat_access ? true : false;
      }
    }
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }
  }
  async ngOnInit() {
    this.id = localStorage.getItem('CisspDomainid');
    this.Ass_id = localStorage.getItem('CisspknowAssId');
    this.RowNumber = localStorage.getItem('CisspknowRowNumber');
    var set = JSON.parse(<string>localStorage.getItem('KnowAssData'));
    this.name = set.knowass_name;
    await this.spinner.show();
    await this.bkplistKnowQues();
  }
  dashbordright_left() {
    if (this.scrWidth < 768) {
      this.dislayhidden = true;
    }
  }
  retuenback() {
    if (this.scrWidth < 768) {
      this.dislayhidden = false;
    }
    this.router.navigate([`/sidenav/knowledge`]);
  }
  async QuestionClick(item, index: number) {
    this.RemainquestionImage = false;
    this.nextQuestionArray = [];
    this.nextQuestionArray.push(this.Knowass[index - 1]);
    this.NextChnageQuestionNo = index - 1;
  }
  async ClickTrue(items) {
    if (window.innerWidth <= 768) {
      this.spinner.show()
    }
    this.sharedDataService.setKnowledgeAssessmentData([])
    this.sharedDataService.setScheduleData([])
    this.sharedDataService.setSharedReviewGuideData([])
    if (!this.CompleteImage) {
      var elmnt = document.getElementById(items.id);
      elmnt.scrollIntoView();
      this.AnswerComplter = 0;
      items.answered = 1;
      this.nextQuestionArray = [];
      this.NextChnageQuestionNo = this.NextChnageQuestionNo + 1;
      this.correct = 0;
      this.incorrct = 0;
      this.Knowass.forEach((element) => {
        if (element.answered == 1) {
          this.AnswerComplter = this.AnswerComplter + 1;
          if ('0' == items.answer) {
            this.correct = this.correct + 1;
          } else {
            this.incorrct = this.incorrct + 1;
          }
        }
      });
      items.user_ans = '0';
      var dataquestion = this.Knowass.filter((item) => item.answered == 0);
      if (dataquestion.length == 0) {
        this.spinner.show()
      } else {
        this.CompleteImage = false;
        if (this.Knowass.length - 1 >= this.NextChnageQuestionNo) {
          this.Disabled = true;
          this.nextQuestionArray.push(this.Knowass[this.NextChnageQuestionNo]);
        } else {
          if (dataquestion && dataquestion.length > 0) {
            this.RemainquestionImage = true;
          }
        }
      }
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();

          this.router.navigate(['/login']);
        } else {
          var token = session
          var correct = items.answer == 'TRUE' ? 1 : 0;
          var cohort_id = localStorage.getItem('cohort_id');
          await this.KnowledgeserviceService.AnswerKnowAss(
            items.id,
            0,
            this.Ass_id,
            this.userid,
            token,
            correct,
            items.d_id,
            items.sd_id,
            items.topic_id,
            cohort_id
          ).then((data) => {
            this.spinner.hide();
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              this.Disabled = false;
              var dataquestion = this.Knowass.filter((item) => item.answered == 0);
              if (dataquestion.length == 0) {
                this.CompleteImage = true;
                this.redirectresult();
              }
            }
          });

        }
        this.spinner.hide();
      });


    } else {
      this.nextQuestionArray = [];
      this.CompleteImage = true;
      this.redirectresult();
    }
  }
  async ClickFalse(items) {
    if (window.innerWidth <= 768) {
      this.spinner.show()
    }
    this.sharedDataService.setKnowledgeAssessmentData([])
    this.sharedDataService.setScheduleData([])
    this.sharedDataService.setSharedReviewGuideData([])
    if (!this.CompleteImage) {
      var elmnt = document.getElementById(items.id);
      elmnt.scrollIntoView();
      this.AnswerComplter = 0;
      items.answered = 1;
      this.nextQuestionArray = [];
      this.NextChnageQuestionNo = this.NextChnageQuestionNo + 1;
      this.correct = 0;
      this.incorrct = 0;
      this.Knowass.forEach((element) => {
        if (element.answered == 1) {
          this.AnswerComplter = this.AnswerComplter + 1;
          if ('1' == items.answer) {
            this.correct = this.correct + 1;
          } else {
            this.incorrct = this.incorrct + 1;
          }
        }
      });
      items.user_ans = '1';

      var dataquestion = this.Knowass.filter((item) => item.answered == 0);
      if (dataquestion.length == 0) {
        this.spinner.show();
      } else {
        this.CompleteImage = false;
        if (this.Knowass.length - 1 >= this.NextChnageQuestionNo) {
          this.Disabled = true;
          this.nextQuestionArray.push(this.Knowass[this.NextChnageQuestionNo]);
        } else {
          if (dataquestion && dataquestion.length > 0) {
            this.RemainquestionImage = true;
          }
        }
      }
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();

          this.router.navigate(['/login']);
        } else {
          var token = session
          var correct = items.answer == 'FALSE' ? 1 : 0;
          var cohort_id = localStorage.getItem('cohort_id');
          await this.KnowledgeserviceService.AnswerKnowAss(
            items.id,
            1,
            this.Ass_id,
            this.userid,
            token,
            correct,
            items.d_id,
            items.sd_id,
            items.topic_id,
            cohort_id
          ).then((data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              this.spinner.hide()
              this.Disabled = false;
              var dataquestion = this.Knowass.filter((item) => item.answered == 0);
              if (dataquestion.length == 0) {
                this.CompleteImage = true;
                this.redirectresult();
              }
            }
            this.spinner.hide()
          });
        }
      });
    } else {
      this.nextQuestionArray = [];
      this.CompleteImage = true;
      this.redirectresult();
    }
  }
  async ClickDKnow(items) {
    if (window.innerWidth <= 768) {
      this.spinner.show()
    }
    this.sharedDataService.setKnowledgeAssessmentData([])
    this.sharedDataService.setScheduleData([])
    this.sharedDataService.setSharedReviewGuideData([])
    if (!this.CompleteImage) {
      var elmnt = document.getElementById(items.id);
      elmnt.scrollIntoView();
      this.AnswerComplter = 0;
      items.answered = 1;
      this.nextQuestionArray = [];
      this.NextChnageQuestionNo = this.NextChnageQuestionNo + 1;
      this.correct = 0;
      this.incorrct = 0;
      this.Knowass.forEach((element) => {
        if (element.answered == 1) {
          this.AnswerComplter = this.AnswerComplter + 1;
          if ('0' == items.answer) {
            this.correct = this.correct + 1;
          } else {
            this.incorrct = this.incorrct + 1;
          }
        }
      });
      items.user_ans = '2';

      var dataquestion = this.Knowass.filter((item) => item.answered == 0);
      if (dataquestion.length == 0) {
        this.spinner.show()
      } else {
        this.CompleteImage = false;
        if (this.Knowass.length - 1 >= this.NextChnageQuestionNo) {
          this.Disabled = true;
          this.nextQuestionArray.push(this.Knowass[this.NextChnageQuestionNo]);
        } else {
          if (dataquestion && dataquestion.length > 0) {
            this.RemainquestionImage = true;
          }
        }
      }
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();

          this.router.navigate(['/login']);
        } else {
          var token = session
          var correct = 2;
          var cohort_id = localStorage.getItem('cohort_id');
          await this.KnowledgeserviceService.AnswerKnowAss(
            items.id,
            2,
            this.Ass_id,
            this.userid,
            token,
            correct,
            items.d_id,
            items.sd_id,
            items.topic_id,
            cohort_id
          ).then((data) => {
            this.spinner.hide();
            this.Disabled = false;
            var dataquestion = this.Knowass.filter((item) => item.answered == 0);
            if (dataquestion.length == 0) {
              this.CompleteImage = true;
              this.redirectresult();
            }
          });
        }
        this.spinner.hide();
      });

    } else {
      this.nextQuestionArray = [];
      this.CompleteImage = true;
      this.redirectresult();
    }
  }

  async result() {
    await this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        var cohort_id = localStorage.getItem('cohort_id');

        this.KnowledgeserviceService.Know_Complete(
          this.Ass_id,
          this.userid,
          token,
          cohort_id
        );
        this.service.testlogs_add(this.userid, this.Ass_id, 'KA', 'END', token);
      }
    });

    let correct = this.Knowass.filter(x => (x.user_ans == 0 ? "TRUE" : x.user_ans == 1 ? "FALSE" : "DON'T KNOW") == x.answer)
    let dKnow = this.Knowass.filter(x => x.user_ans == "2")
    let total = this.Knowass.length;
    let incorrect = total - (correct.length + dKnow.length);

    let correctPer = Math.round((correct.length * 100) / total);
    let dknowPer = Math.round((dKnow.length * 100) / total);
    let incorrectPer = 100 - (correctPer + dknowPer);

    var dataPass = {
      ass_id: this.Ass_id,
      correct: correct.length,
      wrong: incorrect,
      dknow: dKnow.length,
      currect_per: correctPer,
      incurrect_per: incorrectPer,
      dontknow_per: dknowPer,
      total: total,
    }
    var data = btoa(JSON.stringify(dataPass));
    await this.spinner.hide();
    await this.router.navigate([`/sidenav/knowledgeresult/${data}`]);
  }
  async redirectresult() {
    await this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        var cohort_id = localStorage.getItem('cohort_id');

        this.KnowledgeserviceService.Know_Complete(
          this.Ass_id,
          this.userid,
          token,
          cohort_id
        );
        this.service.testlogs_add(this.userid, this.Ass_id, 'KA', 'END', token);
      }
    });
    await this.spinner.hide();
  }

  async bkplistKnowQues() {
    this.newerror = false;

    try {
      this.AnswerComplter = 0;
      this.userid = localStorage.getItem('CisspUserId');
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();

          this.router.navigate(['/login']);
        } else {
          this.correct = 0;
          this.incorrct = 0;
          var token = session
          var cohort_id = localStorage.getItem('cohort_id');
          await this.KnowledgeserviceService.getKnowledgeQuestions(
            this.Ass_id,
            this.userid,
            cohort_id,
            token, this.RowNumber
          ).then(
            async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.Knowass = list.data;
                if (this.Knowass.length > 0) {
                  this.Knowass.forEach((element, index) => {
                    element['SrNo'] = index + 1;
                    if (element.answered == 1) {
                      this.AnswerComplter = this.AnswerComplter + 1;
                      if (element.user_ans == element.answer) {
                        this.correct = this.correct + 1;
                      } else {
                        this.incorrct = this.incorrct + 1;
                      }
                    }
                  });
                  this.QuestionLen = this.Knowass.length;

                  this.NextChnageQuestionNo = 0;
                  if (this.Knowass.length > 0) {
                    var dataquestion = this.Knowass.filter(
                      (item) => item.answered == 0
                    );
                    if (dataquestion.length > 0) {
                      this.NextChnageQuestionNo = dataquestion[0].SrNo - 1;
                      this.nextQuestionArray.push(dataquestion[0]);
                      this.ViewBoolean = false;
                    } else {
                      this.ViewBoolean = true;
                      this.nextQuestionArray.push(
                        this.Knowass[this.NextChnageQuestionNo]
                      );
                    }
                  }
                  await this.spinner.hide();
                } else {
                  this.QuestionLen = this.Knowass.length;
                  await this.spinner.hide();
                }
              } else {
                if (data[0].status == 0) {
                  this.newerror = true;
                } else {
                  this.service.ShowError('Encountered server error!');
                }
                await this.spinner.hide();
              }
            },
            (err) => { }
          );
        }
      });
    } catch (e) { }
  }
  retuey() {
    window.location.reload();
  }
  checkMobileQue() {
    var QuestionLen = document.getElementById("QuestionLen") as Element;
    var nextQuestionArray = document.getElementById("nextQuestionArray") as Element;
    QuestionLen.classList.remove("da-bord-left")
    nextQuestionArray.classList.add("da-bord-right")
  }
  checkQuestionArray() {
    var QuestionLen = document.getElementById("QuestionLen") as Element;
    var nextQuestionArray = document.getElementById("nextQuestionArray") as Element;
    QuestionLen.classList.add("da-bord-left")
    nextQuestionArray.classList.remove("da-bord-right")
  }
}