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 { PracticeserviceService } from '../../services/practice/practiceservice.service';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-practicetestquestionresult',
  templateUrl: './practicetestquestionresult.component.html',
  styleUrls: ['./practicetestquestionresult.component.scss'],
})
export class PracticetestquestionresultComponent implements OnInit {
  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;
  pageNumber = 1;
  pageSize = 5;
  srNumber = 0
  isLoading: number = 0;
  constructor(
    public auth: AuthserviceService,
    public sanitizer: DomSanitizer,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public ActiveRoute: ActivatedRoute,
    public router: Router,
    public PracticeserviceService: PracticeserviceService,
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
    this.userid = localStorage.getItem('CisspUserId');
    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;
      }
    }

    this.service.title = '';
    this.cer_id = localStorage.getItem('CisspCourseId');

    this.ActiveRoute.params.subscribe(async (params) => {
      try {
        var dataPass = JSON.parse(atob(decodeURIComponent(params['testid'])));
        this.testid = dataPass.test_id;
        this.correct = dataPass.currect;
        this.incorrect = dataPass.wrong;
        this.correctper = dataPass.currect_per;
        this.incorrectper = dataPass.incurrect_per;
        this.total = dataPass.total

        if (dataPass.RowNumber)
          this.RowNumber = dataPass.RowNumber;
      } catch (error) {
        this.router.navigate(['sidenav/practicetest']);
      }
    });
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowques: false,
      knowresult: false,
      studentprofile: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      CATresult: false,
      CATQue: false,
      PracticeResult: false,
      Practiceques: false,
      resource: false,
      liveSupport: false
    };
  }
  async ngOnInit() {
    await this.spinner.show();
    await this.IdPracticeTestdata();
    await this.PracticeTestDomainReport();
    await this.listPracticeTestQuestion(this.pageNumber, this.pageSize);
  }

  async 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 {
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = session
          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(pageNumber: number, pageSize: number) {
    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.PracticeserviceService.PracticeTestFiltertestques(
            this.userid,
            this.testid,
            cohort_id,
            token,
            this.RowNumber,
            pageNumber,
            pageSize
          ).then(async (data) => {
            this.isLoading++
            if (data[0].status == 200) {
              var PracticeQuestionlist = [];
              var list = JSON.parse(<string>data[0].json);
              PracticeQuestionlist = list.data;
              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) {
                  } else {
                    this.pending += 1;
                  }
                  if (element.flag_review == 1) {
                    this.Mark += 1;
                  }
                  this.PracticeQuestionlist.push(element);
                  this.bkpPracticeQuestionlist.push(element);
                });
                this.PracticeQuestionlist.sort(
                  (a, b) => a.seq_number - b.seq_number
                );
                this.PracticeQuestionlist.forEach((que, i) => {
                  que['sr_no'] = i + 1;
                });
              }
              if (this.PracticeQuestionlist.length < this.total) {
                this.listPracticeTestQuestion(++this.pageNumber, this.pageSize)
              }
            }

            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 saveDiscussion(item) {
    if (!this.DiscussionText) {
      this.service.ShowError('Message cant not be empty.');
      return;
    } 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,
                'PRACTICE',
                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();
          }
        });
    }
  }
  async IdPracticeTestdata() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        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);
  }
  async savenotes(item) {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        await this.PracticeserviceService.savenotes(
          this.userid,
          this.testid,
          item.id,
          'PRACTICE',
          item.Notes,
          token
        ).then(async (value) => { });
      }
    });
  }
  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 = false;
  }

  MindmappopupClose(event) {
    this.MindmapPopup = false;
  }
  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");
  }
}