import { Component, EventEmitter, Input, OnInit, Output, SimpleChanges } from '@angular/core';

import { ServicesService } from '../../services.service';
import { Router, ActivatedRoute } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';


import { DomSanitizer } from '@angular/platform-browser';
import { KnowledgeService } from 'src/app/services/knowledge/knowledge.service';
import { AuthorizationService } from 'src/app/service/authorization.service';

@Component({
  selector: 'app-student-knowledge-result',
  templateUrl: './student-knowledge-result.component.html',
  styleUrls: ['./student-knowledge-result.component.scss']
})
export class StudentKnowledgeResultComponent implements OnInit {

  @Input() is_popup: any;
  @Output() public onComplete = new EventEmitter<boolean>();
  VideoPopup: boolean = false;
  MindmapPopup: boolean = false;
  id: any;
  cer_id: any;
  userid: any;
  transformMarkedPrg: any;
  name: any;
  correct: any;
  incorrect: any;
  pending: any;
  correctper: any;
  incorrectper: any;
  pendingper: any;
  openMindMap: boolean = false;

  AllQuestion = 0;
  IncorrectQue = 0;
  CorrectQue = 0;
  pendding = 0;
  DonotKnowque = 0;
  KnowassresultShow = [];
  bkpKnowassresultShow = [];

  DiscussionText: any;
  Description: any;
  videoSource = 'https://www.youtube.com/watch?v=dURBDcT6v8Y';
  DonotKnow: any;
  DonotKnowper: any;

  assSummry: boolean = true;
  assResult: boolean = true;
  allQuestion: boolean = true;
  correctQuestion: boolean = false;
  incorrectQuestion: boolean = false;
  dontQuestion: boolean = false;
  RowNumber: any;

  constructor(
    public KnowledgeserviceService: KnowledgeService,
    public sanitizer: DomSanitizer,
    public spinner: NgxSpinnerService,
    public auth: AuthorizationService,
    public service: ServicesService,
    public ActiveRoute: ActivatedRoute,
    public router: Router
  ) {

    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }
    this.correct = 0 + ' ' + 100;
    this.correctper = 0;

    this.incorrect = 0 + ' ' + 100;
    this.incorrectper = 0;
    this.pending = 0 + ' ' + 100;
    this.markper = 0;
    this.correctper = 0;
    this.mark = 0 + ' ' + 100;
    this.DonotKnowper = 0;
    this.DonotKnow = 0 + ' ' + 100;

    if (window.innerWidth <= 767) {
      this.assResult = false;
    }
  }
  gotToChat(item) {
    let q = "Question-" + item.sr_no + ": " + item.question;
    window.sessionStorage.setItem('qdiscuss', q);
    this.router.navigate(['/sidenav/chatting']);
  }
  showSummary() {
    this.assSummry = true;
    this.assResult = false;
  }

  showResult() {
    this.assResult = true;
    this.assSummry = false;
  }

  MindMapClick(mind) {
    this.MindmapPopup = mind;
  }
  Videoclick(vid) {
    this.VideoPopup = vid;
  }
  CloseMindmap() {
    this.openMindMap = false;
  }
  domainreport = [];
  markper: any;
  mark: any;
  Show = 10;
  throttle = 300;
  scrollDistance = 1;
  scrollUpDistance = 2;

  async ngOnInit() {

    localStorage.setItem('CisspUserId', this.is_popup.user_id);
    localStorage.setItem('CisspCourseId', this.is_popup.certi_id);
    localStorage.setItem('CisspknowAssId', this.is_popup.type_id);
    localStorage.setItem('CisspknowRowNumber', "0");
    localStorage.setItem('cohort_id', this.is_popup.cohort_id);
    await this.spinner.show();
    this.name = this.is_popup.exam_name;

    await this.KnowDomainReport();
    await this.listKnowQues();
    await this.KnowassList();
    await this.spinner.hide();
  }
  onScrollDown() {
    this.Show += 1;
  }
  async KnowDomainReport() {
    this.userid = localStorage.getItem('CisspUserId');
    this.cer_id = localStorage.getItem('CisspCourseId');
    this.id = localStorage.getItem('CisspknowAssId');
    this.RowNumber = localStorage.getItem('CisspknowRowNumber');
    var cohort_id = localStorage.getItem('cohort_id');

    try {
      var authenticatedUser = this.auth.getAuthenticatedUser();
      await this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();

            this.router.navigate(['/login']);
          } else {
            var token = ''
            await this.KnowledgeserviceService.KnowDomainReport(
              this.userid,
              this.cer_id,
              this.id,
              this.RowNumber,
              cohort_id,
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                var domainreport = list.data;
                if (domainreport && domainreport.length > 0) {
                  domainreport.forEach((element, index) => {
                    element['Srno'] = index + 1;
                    element['totalProgressCorrect'] = Math.round(
                      (element.currect * 100) / element.total
                    )
                      ? Math.round((element.currect * 100) / element.total)
                      : 0;
                    element['totalProgressIncorrect'] = Math.round(
                      (element.wrong * 100) / element.total
                    )
                      ? Math.round((element.wrong * 100) / element.total)
                      : 0;
                    element['DonotknowProgress'] = Math.round(
                      (element.dontknow * 100) / element.total
                    )
                      ? Math.round((element.dontknow * 100) / element.total)
                      : 0;
                  });
                  this.domainreport = domainreport.filter(
                    (item) =>
                      item.totalProgressCorrect > 0 ||
                      item.totalProgressIncorrect > 0 ||
                      item.DonotknowProgress > 0
                  );
                }
              } else {
                var error = JSON.parse(<string>data[0].json);
                this.service.ShowError(error.message);
              }
            });
          }
        });
    } catch (e) {
      this.service.ShowError(e.meassage);
      await this.spinner.hide();
    }
  }

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

            this.router.navigate(['/login']);
          } else {
            var token = ''
            this.cer_id = localStorage.getItem('CisspCourseId');
            var cohort_id = localStorage.getItem('cohort_id');

            await this.KnowledgeserviceService.ListKnowAssCerfication(
              this.userid,
              this.cer_id,
              cohort_id,
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                var totalper = 0;
                var Knoewlist = [];
                if (list.data && list.data.length > 0) {
                  list.data.forEach((element) => {
                    if (element.schedule.length > 0) {
                      if (element.total && element.total && element.currect) {
                        element['currectper'] = Math.round(
                          (element.currect * 100) / element.total
                        )
                          ? Math.round((element.currect * 100) / element.total)
                          : 0;
                        totalper += element['currectper'];
                      } else {
                        element['currectper'] = 0;
                        totalper += element['currectper'];
                      }
                      Knoewlist.push(element);
                    }
                  });
                  this.mark = '' + 100 * 2 + ',200';
                  if (totalper && Knoewlist.length) {
                    this.markper = Math.round(totalper / Knoewlist.length);
                    this.mark = this.markper + ' ' + (100 - this.markper);
                  } else {
                    this.markper = 0;
                    this.mark = 0 + ' ' + 100;
                  }
                }
              }
            });
            await this.spinner.hide();
          }
        });
    } catch (e) {
      await this.spinner.hide();
    }
  }

  async listKnowQues() {
    try {
      this.userid = localStorage.getItem('CisspUserId');
      var authenticatedUser = this.auth.getAuthenticatedUser();

      await this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();

            this.router.navigate(['/login']);
          } else {
            this.AllQuestion = 0;
            this.IncorrectQue = 0;
            this.CorrectQue = 0;
            this.pendding = 0;
            var token = ''
            var cohort_id = localStorage.getItem('cohort_id');
            await this.KnowledgeserviceService.FilterKnowQueResultShow(
              this.id,
              this.userid,
              cohort_id,
              token,
              this.RowNumber
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                var KnowassresultShow = list.data;
                KnowassresultShow.forEach((element, i) => {
                  element['sr_no'] = i + 1;
                  element['check'] = false;
                  if (element.StudyMaterials.length > 0) {
                    element.StudyMaterials.forEach((sum) => {
                      sum.content = this.sanitizer.bypassSecurityTrustHtml(
                        sum.content
                      );
                    });
                  }
                  if (element.Video && element.Video.length > 0) {
                    element.Video.forEach((vid) => {
                      vid['sd_id'] = element.sd_id;
                      var link = '';
                      link = vid.video_link;
                      if (link.includes('cisspupload')) {
                        vid['youTube'] = false;
                      }
                      vid['topic_list'] = JSON.parse(
                        vid.topic_list
                      )
                        ? JSON.parse(vid.topic_list)
                        : [];
                    });
                  }
                  if (element.answered == 1) {
                    this.AllQuestion = this.AllQuestion + 1;
                    if (element.answer == 'FALSE') {
                      element.answer = '1';
                    } else if (element.answer == 'TRUE') {
                      element.answer = '0';
                    }

                    if (element.user_ans == '2') {
                      this.DonotKnowque += 1;
                    } else {
                      if (element.user_ans == element.answer) {
                        this.CorrectQue = this.CorrectQue + 1;
                      } else {
                        this.IncorrectQue = this.IncorrectQue + 1;
                      }
                    }

                    this.KnowassresultShow.push(element);
                    this.bkpKnowassresultShow.push(element);
                  } else {
                    this.pendding += 1;
                  }
                });
                var correct =
                  (this.CorrectQue * 100) /
                    (this.CorrectQue +
                      this.IncorrectQue +
                      this.DonotKnowque +
                      this.pendding)
                    ? (this.CorrectQue * 100) /
                    (this.CorrectQue +
                      this.IncorrectQue +
                      this.DonotKnowque +
                      this.pendding)
                    : 0;
                this.correct =
                  correct.toString() + ' ' + (100 - correct).toString();

                var incorrect =
                  (this.IncorrectQue * 100) /
                    (this.CorrectQue +
                      this.IncorrectQue +
                      this.DonotKnowque +
                      this.pendding)
                    ? (this.IncorrectQue * 100) /
                    (this.CorrectQue +
                      this.IncorrectQue +
                      this.DonotKnowque +
                      this.pendding)
                    : 0;
                this.incorrect =
                  incorrect.toString() + ' ' + (100 - incorrect).toString();

                var pending =
                  (this.pendding * 100) /
                    (this.CorrectQue +
                      this.IncorrectQue +
                      this.DonotKnowque +
                      this.pendding)
                    ? (this.pendding * 100) /
                    (this.CorrectQue +
                      this.IncorrectQue +
                      this.DonotKnowque +
                      this.pendding)
                    : 0;
                this.pending =
                  pending.toString() + ' ' + (100 - pending).toString();


                this.correctper = Math.round(
                  (this.CorrectQue * 100) /
                  (this.CorrectQue +
                    this.IncorrectQue +
                    this.pendding +
                    this.DonotKnowque)
                );
                this.incorrectper = Math.round(
                  (this.IncorrectQue * 100) /
                  (this.CorrectQue +
                    this.IncorrectQue +
                    this.pendding +
                    this.DonotKnowque)
                );
                this.pendingper = Math.round(
                  (this.pendding * 100) /
                  (this.CorrectQue +
                    this.IncorrectQue +
                    this.pendding +
                    this.DonotKnowque)
                );
                this.DonotKnowper = Math.round(
                  (this.DonotKnowque * 100) /
                  (this.CorrectQue +
                    this.IncorrectQue +
                    this.pendding +
                    this.DonotKnowque)
                );

                this.DonotKnow =
                  this.DonotKnowper.toString() +
                  ' ' +
                  (100 - this.DonotKnowper).toString();
              } else {
              }
            });
          }
        });
    } catch (e) {
      this.spinner.hide();
    }
  }
  filerResult(item) {
    this.KnowassresultShow = [];
    this.allQuestion = false;
    this.correctQuestion = false;
    this.incorrectQuestion = false;
    this.dontQuestion = false;
    if (item == 'dont') {
      this.dontQuestion = true;
      this.bkpKnowassresultShow.forEach((element) => {
        if (element.user_ans == '2') {
          this.KnowassresultShow.push(element);
        }
      });
    } else if (item == 'correct') {
      this.correctQuestion = true;
      this.bkpKnowassresultShow.forEach((element) => {
        if (element.user_ans == element.answer && element.user_ans != '2') {
          this.KnowassresultShow.push(element);
        }
      });
    } else if (item == 'incorrect') {
      this.incorrectQuestion = true;
      this.bkpKnowassresultShow.forEach((element) => {
        if (element.user_ans != element.answer && element.user_ans != '2') {
          this.KnowassresultShow.push(element);
        }
      });
    } else {
      this.allQuestion = true;
      this.KnowassresultShow = this.bkpKnowassresultShow;
    }
    this.KnowassresultShow.sort((a, b) => a.sr_no - b.sr_no);
  }
  checkboxchange(item) {
    this.KnowassresultShow.forEach((element) => {
      element.check = false;
    });
    item.check = !item.check;
  }
  TabPopUPMobile(item) {
    item.check = false;
  }

  retuey() {
    window.location.reload();
  }

  popupClose(event) {
    this.VideoPopup = event;
  }

  MindmappopupClose(event) {
    this.MindmapPopup = event;
  }

  QuestionRWQ() {
    document.getElementById("questionshow").classList.toggle("show");
  }
  ngOnChanges(changes: SimpleChanges): void {

    if (this.is_popup) {
      if (changes.is_popup.previousValue) {
        this.correct = 0 + ' ' + 100;
        this.correctper = 0;

        this.incorrect = 0 + ' ' + 100;
        this.incorrectper = 0;
        this.pending = 0 + ' ' + 100;
        this.markper = 0;
        this.correctper = 0;
        this.mark = 0 + ' ' + 100;
        this.DonotKnowper = 0;
        this.DonotKnow = 0 + ' ' + 100;
        this.AllQuestion = 0;
        this.IncorrectQue = 0;
        this.CorrectQue = 0;
        this.pendding = 0;
        this.DonotKnowque = 0;
        this.KnowassresultShow = [];
        this.bkpKnowassresultShow = [];
        this.domainreport = [];
        this.Show = 10;
        this.throttle = 300;
        this.scrollDistance = 1;
        this.scrollUpDistance = 2;
        this.ngOnInit();
      }
    }
  }
}
