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 { AuthorizationService } from 'src/app/service/authorization.service';

import { DomSanitizer } from '@angular/platform-browser';
import { PracticeService } from 'src/app/services/practice/practice.service';

@Component({
  selector: 'app-student-practice-result',
  templateUrl: './student-practice-result.component.html',
  styleUrls: ['./student-practice-result.component.scss']
})
export class StudentPracticeResultComponent implements OnInit {
  @Input() is_popup: any;
  @Output() public onComplete = new EventEmitter<boolean>();

  VideoPopup: boolean = false;
  MindmapPopup: boolean = false;
  throttle = 300;
  scrollDistance = 1;
  scrollUpDistance = 2;
  Show = 10;

  DomainReport = [];
  userid: any;
  testid: any;
  PracticeQuestionlist = [];
  bkpPracticeQuestionlist = [];

  correct = 0;
  incorrect = 0;
  correctper = 0;
  incorrectper = 0;

  pending = 0;
  total = 0;
  DiscussionText: any;

  openMindMap: boolean = false;
  Description: any;
  data: any;
  name: any;
  cer_id: any;
  allQuestion: boolean = true;
  correctQuestion: boolean = false;
  incorrectQuestion: boolean = false;
  MarkQuestion: boolean = false;
  PenddingQuestion: boolean = false;
  Mark = 0;
  type: any;
  RowNumber: any = 0;
  constructor(
    public auth: AuthorizationService,
    public sanitizer: DomSanitizer,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public ActiveRoute: ActivatedRoute,
    public router: Router,
    public PracticeserviceService: PracticeService
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
  }
  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);
    this.userid = this.is_popup.user_id;
    this.cer_id = this.is_popup.certi_id;
    this.testid = this.is_popup.type_id;
    await this.spinner.show();
    await this.IdPracticeTestdata();
    await this.PracticeTestDomainReport();
    await this.listPracticeTestQuestion();
  }
  onScrollDown() {
    this.Show += 1;
  }
  MindMapClick(mind) {
    this.MindmapPopup = mind;
    var data = btoa(JSON.stringify(mind.id));
    this.router.navigate([`/mindmaps/${data}`]);
  }
  Videoclick(vid) {
    this.VideoPopup = vid;
  }
  CloseMindmap() {
    this.openMindMap = false;
  }
  async PracticeTestDomainReport() {
    this.DomainReport = [];
    try {
      var authenticatedUser = this.auth.getAuthenticatedUser();
      if (authenticatedUser == null) {
        this.router.navigate(['/login']);
      } else {
        authenticatedUser.getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          }
          const headers = new Headers();
          var that = this;
          this.auth.getAuthenticatedUser().getSession(async (err, session) => {
            if (err) {
              await this.spinner.hide();
              this.router.navigate(['/login']);
            } else {
              var token = ''
              await this.PracticeserviceService.DomainFiltertestques(
                this.userid,
                this.testid,
                this.cer_id,
                token
              ).then(async (data) => {
                if (data[0].status == 200) {
                  var list = JSON.parse(<string>data[0].json);
                  await list.data.forEach((element) => {
                    if (element.currect || element.wrong) {
                      if (element.currect != 0) {
                        element['CorrectPer'] = Math.round(
                          (element.currect * 100) / element.total
                        );
                      } else {
                        element['CorrectPer'] = 0;
                      }
                      if (element.wrong != 0) {
                        element['InCorrectPer'] = 100 - Math.round(
                          (element.currect * 100) / element.total
                        );
                      } else {
                        element['InCorrectPer'] = 0;
                      }
                      this.DomainReport.push(element);
                    }
                  });
                }
              });
            }
          });
        });
      }
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }
  }
  async listPracticeTestQuestion() {
    try {
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = ''
          var cohort_id = localStorage.getItem('cohort_id');
          await this.PracticeserviceService.PracticeTestFiltertestques(
            this.userid,
            this.testid,
            cohort_id,
            token,
            this.RowNumber,
          ).then(async (data) => {
            if (data[0].status == 200) {
              var PracticeQuestionlist = [];
              var list = JSON.parse(<string>data[0].json);
              PracticeQuestionlist = list.data;

              this.correct = 0;
              this.incorrect = 0;
              this.pending = 0;
              this.total = PracticeQuestionlist.length;
              if (PracticeQuestionlist.length > 0) {
                PracticeQuestionlist.forEach((element) => {
                  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;
                      vid['topic_list'] = JSON.parse(
                        vid.topic_list
                      )
                        ? JSON.parse(vid.topic_list)
                        : [];
                    });
                  }
                  if (element.answered == 1) {
                    if (element.user_ans == element.answer) {
                      this.correct += 1;
                    } else if (element.user_ans != element.answer) {
                      this.incorrect += 1;
                    }
                  } else {
                    this.pending += 1;
                  }
                  if (element.flag_review == 1) {
                    this.Mark += 1;
                  }
                  this.PracticeQuestionlist.push(element);
                  this.bkpPracticeQuestionlist.push(element);
                });
                this.correctper = Math.round((this.correct * 100) / this.total);
                this.incorrectper = Math.round(
                  (this.incorrect * 100) / this.total
                );

                this.PracticeQuestionlist.sort(
                  (a, b) => a.seq_number - b.seq_number
                );
                this.PracticeQuestionlist.forEach((que, i) => {
                  que['sr_no'] = i + 1;
                });
              }
            }

            await this.spinner.hide();
          });
        }
      });
      var authenticatedUser = this.auth.getAuthenticatedUser();
      if (authenticatedUser == null) {
        this.router.navigate(['/login']);
      } else {
      }
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }
  }
  async IdPracticeTestdata() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = ''

        await this.PracticeserviceService.IdPracticeTest(
          this.testid,
          token
        ).then(async (value) => {
          if (value[0].status == 200) {
            var list = JSON.parse(<string>value[0].json);

            this.name = list.data.practice_name;
            this.type = list.data.type;
          } else {
            await this.spinner.hide();
          }
        });
      }
    });
  }
  filerResult(item) {
    this.PracticeQuestionlist = [];
    this.allQuestion = false;
    this.correctQuestion = false;
    this.incorrectQuestion = false;
    this.MarkQuestion = false;
    this.PenddingQuestion = false;
    if (item == 'correct') {
      this.correctQuestion = true;
      this.bkpPracticeQuestionlist.forEach((element) => {
        if (element.user_ans == element.answer && element.answered == 1) {
          this.PracticeQuestionlist.push(element);
        }
      });
    } else if (item == 'incorrect') {
      this.incorrectQuestion = true;
      this.bkpPracticeQuestionlist.forEach((element) => {
        if (element.user_ans != element.answer && element.answered == 1) {
          this.PracticeQuestionlist.push(element);
        }
      });
    } else if (item == 'Mark') {
      this.MarkQuestion = true;
      this.bkpPracticeQuestionlist.forEach((element, index) => {
        if (element.flag_review == 1) {
          this.PracticeQuestionlist.push(element);
        }
      });
    } else if (item == 'Pending') {
      this.PenddingQuestion = true;
      this.bkpPracticeQuestionlist.forEach((element) => {
        if (!element.answered) {
          this.PracticeQuestionlist.push(element);
        }
      });
    } else {
      this.allQuestion = true;
      this.PracticeQuestionlist = this.bkpPracticeQuestionlist;
    }
    this.PracticeQuestionlist.sort((a, b) => a.seq_number - b.seq_number);
  }
  checkboxchange(item) {
    this.PracticeQuestionlist.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;
  }
  gotToChat(item) {
    let q = "Question-" + item.sr_no + ": " + item.title;
    window.sessionStorage.setItem('qdiscuss', q);
    this.router.navigate(['/sidenav/chatting']);
  }
  QuestionRWQ() {
    document.getElementById("questionshow").classList.toggle("show");
  }


  ngOnChanges(changes: SimpleChanges): void {
    if (this.is_popup) {
      if (changes.is_popup.previousValue) {
        this.throttle = 300;
        this.scrollDistance = 1;
        this.scrollUpDistance = 2;
        this.Show = 10;

        this.DomainReport = [];
        this.PracticeQuestionlist = [];
        this.bkpPracticeQuestionlist = [];

        this.correct = 0;
        this.incorrect = 0;
        this.correctper = 0;
        this.incorrectper = 0;

        this.pending = 0;
        this.total = 0;
        this.Mark = 0;
        this.RowNumber = 0;
        this.ngOnInit();
      }
    }
  }
}
