import { Component, OnInit } from '@angular/core';
import { ServicesService } from '../../services.service';
import { Router, ActivatedRoute } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { AuthserviceService } from '../../authservice.service';
import { CatexamService } from '../../services/CAT/catexam.service';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'app-cateexamresult',
  templateUrl: './cateexamresult.component.html',
  styleUrls: ['./cateexamresult.component.scss'],
})
export class CateexamresultComponent implements OnInit {
  VideoPopup: boolean = false;
  MindmapPopup: boolean = false;
  DomainReport = [];
  userid: any;
  testid: any;
  PracticeQuestionlist = [];
  bkpKnowassresultShow = [];
  correct = 0;
  incorrect = 0;
  pending = 0;
  total = 0;
  DiscussionText: any;
  Description: any;
  openMindMap = false;
  allQuestion: boolean = true;
  correctQuestion: boolean = false;
  incorrectQuestion: boolean = false;
  constructor(
    public sanitizer: DomSanitizer,
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public ActiveRoute: ActivatedRoute,
    public router: Router,
    public CatexamService: CatexamService
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
    this.userid = localStorage.getItem('CisspUserId');
    this.service.title = "<p class='HeaderUser'> <span>  CAT EXAM Summary</span></p>";
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      knowques: false,
      knowresult: false,
      cat: false,
      datestring: false,
      CATresult: true,
      CATQue: false,
      PracticeResult: false,
      studentprofile: false,
      Practiceques: false,
      resource: false,
      liveSupport: false
    };
    this.ActiveRoute.params.subscribe(async (params) => {
      try {
        this.testid = JSON.parse(atob(decodeURIComponent(params['testid'])));
      } catch (error) {
        this.router.navigate(['sidenav/practicetest']);
      }
    });
    this.service.headershow = true;
    this.service.SearchValue = true;
    var access = window.localStorage.getItem('accessitem');
    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;
      }
    }
  }
  MindMapClick(mind) {
    this.MindmapPopup = mind;
  }
  Videoclick(vid) {
    this.VideoPopup = vid;
  }
  CloseMindmap() {
    this.openMindMap = false;
  }
  async ngOnInit() {
    await this.spinner.show();
    await this.PracticeTestDomainReport();
    await this.listPracticeTestQuestion();
  }
  async PracticeTestDomainReport() {
    this.DomainReport = [];
    try {
      this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            let c_id = localStorage.getItem('CisspCourseId');
            var token = session
            var cohort_id = localStorage.getItem('cohort_id');
            await this.CatexamService.DomainFilterCATEXAMA_ANS(
              this.userid,
              this.testid,
              c_id,
              cohort_id,
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.DomainReport = list.data;
                await this.DomainReport.forEach((element) => {
                  if (element.currect != 0) {
                    element['CorrectPer'] = Math.round(
                      (element.currect * 100) / element.total
                    );
                  } else {
                    element['CorrectPer'] = 0;
                  }
                  if (element.wrong != 0) {
                    element['InCorrectPer'] = Math.round(
                      (element.wrong * 100) / element.total
                    );
                  } else {
                    element['InCorrectPer'] = 0;
                  }
                });
              }
            });
          }
        });
    } 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 = session
          var cohort_id = localStorage.getItem('cohort_id');
          await this.CatexamService.CateExamFiltertestques(
            this.userid,
            this.testid,
            cohort_id,
            token
          ).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) => {
                  if (element.Video && element.Video.length > 0) {
                    element.Video.forEach((vid) => {
                      vid['topic_list'] = JSON.parse(
                        vid.topic_list
                      )
                        ? JSON.parse(vid.topic_list)
                        : [];
                    });
                  }
                  if (element.StudyMaterials.length > 0) {
                    element.StudyMaterials.forEach((sum) => {
                      sum.content = this.sanitizer.bypassSecurityTrustHtml(
                        sum.content
                      );
                    });
                  }
                  if (element.answered == 1) {
                    if (element.user_ans == element.answer) {
                      this.correct += 1;
                    } else if (element.user_ans != element.answer) {
                      this.incorrect += 1;
                    }
                    this.PracticeQuestionlist.push(element);
                    this.bkpKnowassresultShow.push(element);
                  } else {
                    this.pending += 1;
                  }
                });
              }
            }
            await this.spinner.hide();
          });
        }
      });
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }
  }
  async saveDiscussion(item) {
    if (
      this.DiscussionText == '' ||
      this.DiscussionText == null ||
      this.DiscussionText == undefined
    ) {
      this.service.ShowError('Message cant not be empty.');
    } else {
      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
            await this.service
              .saveDiscussion(
                this.userid,
                'CAT',
                item.test_id,
                item.id,
                this.DiscussionText,
                token
              )
              .then(async (data) => {
                if (data[0].status == 200) {
                  var list = JSON.parse(<string>data[0].json);
                  let details = JSON.parse(localStorage.getItem('userdetails'));
                  var disc = {
                    createdAt: list.data.createdAt,
                    id: list.data.id,
                    message: list.data.message,
                    q_id: list.data.q_id,
                    status: list.data.status,
                    test_id: list.data.test_id,
                    test_type: list.data.test_type,
                    user_id: list.data.user_id,
                    user: {
                      avatar_url: details.avatar_url,
                      email: details.email,
                      id: details.id,
                      name: details.name,
                    },
                  };
                  this.PracticeQuestionlist.forEach((element) => {
                    if (element.id == list.data.q_id) {
                      element.Discussion.push(disc);
                    }
                  });
                }
                this.DiscussionText = '';
              });
            this.spinner.hide();
          }
        });
    }
  }
  retuey() {
    window.location.reload();
  }
  TabPopUPMobile(item) {
    item.check = false;
  }
  checkboxchange(item) {
    this.PracticeQuestionlist.forEach((element) => {
      element.check = false;
    });
    item.check = !item.check;
  }
  popupClose(event) {
    this.VideoPopup = event;
  }
  MindmappopupClose(event) {
    this.MindmapPopup = event;
  }
  QuestionRWQ() {
    document.getElementById("questionshow").classList.toggle("show");
  }
  filerResult(item) {
    this.PracticeQuestionlist = [];
    this.allQuestion = false;
    this.correctQuestion = false;
    this.incorrectQuestion = false;
    if (item == 'correct') {
      this.correctQuestion = true;
      this.bkpKnowassresultShow.forEach((element) => {
        if (element.user_ans == element.answer && element.user_ans != '2') {
          this.PracticeQuestionlist.push(element);
        }
      });
    } else if (item == 'incorrect') {
      this.incorrectQuestion = true;
      this.bkpKnowassresultShow.forEach((element) => {
        if (element.user_ans != element.answer && element.user_ans != '2') {
          this.PracticeQuestionlist.push(element);
        }
      });
    } else {
      this.allQuestion = true;
      this.PracticeQuestionlist = this.bkpKnowassresultShow;
    }
    this.PracticeQuestionlist.sort((a, b) => a.sr_no - b.sr_no);
  }
}
