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 { DomSanitizer } from '@angular/platform-browser';
import { KnowledgeserviceService } from '../../services/knowledge/knowledgeservice.service';
@Component({
  selector: 'app-knowledgeresult',
  templateUrl: './knowledgeresult.component.html',
  styleUrls: ['./knowledgeresult.component.scss'],
})
export class KnowledgeresultComponent implements OnInit {
  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;
  total = 0;
  KnowassresultShow = [];
  bkpKnowassresultShow = [];
  bkpKnowassresultShowDomain = [];

  DiscussionText: any;
  Description: any;
  DonotKnow: any;
  DonotKnowper: any;

  assSummry: boolean = false;
  assResult: boolean = true;
  allQuestion: boolean = true;
  correctQuestion: boolean = false;
  incorrectQuestion: boolean = false;
  dontQuestion: boolean = false;
  RowNumber: any;
  isLoaded: boolean = false;
  pageNumber: number = 1;
  pageSize: number = 5;

  constructor(
    public KnowledgeserviceService: KnowledgeserviceService,
    public sanitizer: DomSanitizer,
    public spinner: NgxSpinnerService,
    public auth: AuthserviceService,
    public service: ServicesService,
    public ActiveRoute: ActivatedRoute,
    public router: Router
  ) {
    this.service.title =
      "<p class='HeaderUser'> <span>Knowledge Assessments (" +
      0 +
      ')</span></p>';

    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;
      }
    }
    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;
    }

    this.ActiveRoute.params.subscribe(async (params) => {
      try {
        var dataPass = JSON.parse(atob(params['data']));
        this.CorrectQue = dataPass.correct;
        this.IncorrectQue = dataPass.wrong;
        this.DonotKnowque = dataPass.dknow;
        this.correctper = dataPass.currect_per;
        this.incorrectper = dataPass.incurrect_per;
        this.DonotKnowper = dataPass.dontknow_per;
        this.total = dataPass.total

        this.DonotKnow = this.DonotKnowper.toString() + ' ' + (100 - this.DonotKnowper).toString();
        this.incorrect = this.incorrectper.toString() + ' ' + (100 - this.incorrectper).toString();
        this.correct = this.correctper.toString() + ' ' + (100 - this.correctper).toString();
        if (dataPass.RowNumber)
          this.RowNumber = dataPass.RowNumber;


      } catch (error) {
        this.router.navigate(['sidenav/knowledgeresult']);
      }
    });

    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      CATresult: false,
      CATQue: false,
      knowques: false,
      knowresult: true,
      PracticeResult: false,
      studentprofile: false,
      Practiceques: false,
      resource: false,
      liveSupport: 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() {
    var set = JSON.parse(<string>localStorage.getItem('KnowAssData'));
    this.name = set.knowass_name;

    await this.KnowDomainReport();
    await this.listKnowQues(this.pageNumber, this.pageSize);
    await this.KnowassList();
    await this.spinner.hide();
  }
  onScrollDown() {
    this.Show += 1;
  }
  onshowMore() {
    this.Show += 10;
  }
  async domainClick(item) {
    this.domainreport.forEach((element) => {
      if (element.d_id == item.d_id) element.checked = !item.checked;
    });
    let length = this.domainreport.filter((x) => x.checked == true).length;
    if (length > 0) {
      this.KnowassresultShow = [];
      this.bkpKnowassresultShowDomain = [];
      this.AllQuestion = 0;
      this.DonotKnowque = 0;
      this.CorrectQue = 0;
      this.IncorrectQue = 0;
      this.pendding = 0;
      this.domainreport.forEach((domain) => {
        if (domain.checked) {
          this.bkpKnowassresultShow.forEach((element) => {
            if (domain.d_id == element.d_id) {
              if (element.answered == 1) {
                this.AllQuestion = this.AllQuestion + 1;

                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;
                  }
                }
              } else {
                this.pendding += 1;
              }
              this.KnowassresultShow.push(element);
              this.bkpKnowassresultShowDomain.push(element);
            }
          });
        }
      });
      this.allQuestion = true;
      this.correctQuestion = false;
      this.incorrectQuestion = false;
      this.dontQuestion = false;
      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 {
      this.KnowassresultShow = [];
      this.AllQuestion = 0;
      this.DonotKnowque = 0;
      this.CorrectQue = 0;
      this.IncorrectQue = 0;
      this.pendding = 0;
      this.allQuestion = true;
      this.correctQuestion = false;
      this.incorrectQuestion = false;
      this.dontQuestion = false;
      this.bkpKnowassresultShow.forEach((element) => {
        if (element.answered == 1) {
          this.AllQuestion = this.AllQuestion + 1;

          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;
            }
          }
        } else {
          this.pendding += 1;
        }
        this.KnowassresultShow.push(element);
      });
      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();
    }
  }
  async KnowDomainReport() {
    this.spinner.show();
    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 {
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = session
          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['checked'] = false;
                  element['Srno'] = index + 1;
                  // calculation based on domain
                  let singleDomain =
                    element.currect + element.wrong + element.dontknow;

                  let correct = Math.round(
                    (element.currect * 100) / singleDomain
                  )
                    ? Math.round((element.currect * 100) / singleDomain)
                    : 0;

                  let incorrect = Math.round(
                    (element.wrong * 100) / singleDomain
                  )
                    ? Math.round((element.wrong * 100) / singleDomain)
                    : 0;

                  let dontKnow = Math.round(
                    (element.dontknow * 100) / singleDomain
                  )
                    ? Math.round((element.dontknow * 100) / singleDomain)
                    : 0;

                  let total = Math.round(correct + incorrect + dontKnow);
                  // Calculate the difference between the total and 100
                  let diff = 100 - total;
                  // Adjust one of the values to make the total 100
                  if (diff !== 0) {
                    if (diff > 0) {
                      // Add the difference to the value with the highest decimal part
                      if (
                        correct % 1 > incorrect % 1 &&
                        correct % 1 > dontKnow % 1
                      ) {
                        correct += diff;
                      } else if (
                        incorrect % 1 > correct % 1 &&
                        incorrect % 1 > dontKnow % 1
                      ) {
                        incorrect += diff;
                      } else {
                        dontKnow += diff;
                      }
                    } else {
                      // Distribute the negative difference to the values starting from the largest
                      let values = [correct, incorrect, dontKnow];
                      values.sort((a, b) => (b % 1) - (a % 1));
                      let i = 0;
                      while (diff < 0) {
                        if (values[i] > 0) {
                          values[i] += diff;
                          diff = values[i] < 0 ? values[i] : 0;
                        }
                        i++;
                      }
                      [correct, incorrect, dontKnow] = values;
                    }
                  }
                  element['totalProgressCorrect'] = Math.round(
                    (element.currect * 100) / singleDomain
                  )
                    ? correct
                    : 0;
                  element['totalProgressIncorrect'] = Math.round(
                    (element.wrong * 100) / singleDomain
                  )
                    ? incorrect
                    : 0;
                  element['DonotknowProgress'] = Math.round(
                    (element.dontknow * 100) / singleDomain
                  )
                    ? dontKnow
                    : 0;
                });
                this.domainreport = domainreport.filter(
                  (item) =>
                    item.totalProgressCorrect > 0 ||
                    item.totalProgressIncorrect > 0 ||
                    item.DonotknowProgress > 0
                );
                if (this.domainreport.length > 1) {
                  this.assSummry = true;
                }
              }
              this.spinner.hide();
            } else {
              var error = JSON.parse(<string>data[0].json);
              this.service.ShowError(error.message);
              this.spinner.hide();
            }
          });
        }
      });
    } catch (e) {
      this.service.ShowError(e.meassage);
      await this.spinner.hide();
    }
  }

  async KnowassList() {
    try {
      this.spinner.show();
      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 = session
            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.service.title =
                    "<p class='HeaderUser'> <span>Knowledge Assessments (" +
                    Knoewlist.length +
                    ')</span></p>';
                  this.service.knnowlength = Knoewlist.length;

                  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;
                  }
                }
                this.spinner.hide();
              }
            });
            await this.spinner.hide();
          }
        });
    } catch (e) {
      await this.spinner.hide();
    }
  }
  async listKnowQues(pageNumber: number, pageSize: number) {
    try {
      this.spinner.show()
      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 = session
            var cohort_id = localStorage.getItem('cohort_id');
            await this.KnowledgeserviceService.getKnowResultPagination(
              this.id,
              this.userid,
              cohort_id,
              token,
              this.RowNumber,
              pageNumber,
              pageSize
            ).then(async (data) => {
              if (data[0].status == 200) {
                this.isLoaded = true
                var KnowassresultShow = [];
                var list = JSON.parse(<string>data[0].json);
                KnowassresultShow = list.data;
                if (KnowassresultShow.length > 0) {
                  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';
                      }

                      this.KnowassresultShow.push(element);
                      this.bkpKnowassresultShow.push(element);
                    } else {
                      this.pendding += 1;
                    }
                  });
                  this.KnowassresultShow.sort(
                    (a, b) => a.seq_number - b.seq_number
                  );
                  this.KnowassresultShow.forEach((que, i) => {
                    que['sr_no'] = i + 1;
                  });

                }
                if (this.KnowassresultShow.length < this.total) {
                  this.listKnowQues(++this.pageNumber, this.pageSize)
                }
                await this.spinner.hide();
              } else {
                await this.spinner.hide();
              }
            });
          }
        });
    } catch (e) {
      this.spinner.hide();
    }
  }
  async saveDiscussion(item) {
    if (
      this.DiscussionText == '' ||
      this.DiscussionText == null ||
      this.DiscussionText == undefined
    ) {
      this.service.ShowError('Message could 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,
                'KA',
                item.ass_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.KnowassresultShow.forEach((element) => {
                    if (element.ass_id.indexOf(list.data.test_id) != -1) {
                      element.Discussion.push(disc);
                    }
                  });
                }
                this.DiscussionText = '';
              });
            this.spinner.hide();
          }
        });
    }
  }
  filerResult(item) {
    let length = this.domainreport.filter((x) => x.checked == true).length;
    if (length > 0) {
      this.KnowassresultShow = [];
      this.allQuestion = false;
      this.correctQuestion = false;
      this.incorrectQuestion = false;
      this.dontQuestion = false;
      if (item == 'dont') {
        this.dontQuestion = true;
        this.bkpKnowassresultShowDomain.forEach((element) => {
          if (element.user_ans == '2') {
            this.KnowassresultShow.push(element);
          }
        });
      } else if (item == 'correct') {
        this.correctQuestion = true;
        this.bkpKnowassresultShowDomain.forEach((element) => {
          if (element.user_ans == element.answer && element.user_ans != '2') {
            this.KnowassresultShow.push(element);
          }
        });
      } else if (item == 'incorrect') {
        this.incorrectQuestion = true;
        this.bkpKnowassresultShowDomain.forEach((element) => {
          if (element.user_ans != element.answer && element.user_ans != '2') {
            this.KnowassresultShow.push(element);
          }
        });
      } else {
        this.allQuestion = true;
        this.KnowassresultShow = this.bkpKnowassresultShowDomain;
      }
      this.KnowassresultShow.sort((a, b) => a.sr_no - b.sr_no);
    } else {
      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 = false;
  }
  MindmappopupClose(event) {
    this.MindmapPopup = false;
  }
  QuestionRWQ() {
    document.getElementById('questionshow').classList.toggle('show');
  }
}
