import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {
  FormBuilder
} from '@angular/forms';
import { NgxSpinnerService } from 'ngx-spinner';
import { ServicesService } from '../../services.service';
import { AuthserviceService } from '../../authservice.service';
import { SidenavComponent } from '../../components/sidenav/sidenav.component';
import { KnowledgeserviceService } from '../../services/knowledge/knowledgeservice.service';
import { SharedDataService } from 'src/app/services/SharedData/shared-data.service';
@Component({
  selector: 'app-knowledge',
  templateUrl: './knowledge.component.html',
  styleUrls: ['./knowledge.component.scss'],
})
export class KnowledgeComponent implements OnInit {
  Summery: boolean = false;
  PaymentAccess: boolean = false;
  Knowasslist = [];
  KnowassLen = 0;
  id: any;
  userid: any;
  cer_id: any;
  ResetNamedata: any;
  resetResult = false;
  newerror = false;
  @ViewChild(SidenavComponent, { static: true })
  headerComponent: SidenavComponent;
  noFound = false;
  ViewHistory: boolean = false;
  NoPrevRecordFound: boolean = false;
  resetDatalist = [];
  KnowledgeName = "";
  course_type: any;
  constructor(
    public KnowledgeserviceService: KnowledgeserviceService,
    public ActiveRoute: ActivatedRoute,
    public service: ServicesService,
    public auth: AuthserviceService,
    public spinner: NgxSpinnerService,
    public fb: FormBuilder,
    public router: Router,
    public sharedDataService: SharedDataService
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }
    this.service.title = '';
    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;
      }
    }
  }
  ngAfterViewInit() { }
  ngOnDestroy() {
    this.service.title = '';
    this.spinner.hide();
  }
  closeResult() {
    this.resetResult = false;
  }
  async ngOnInit() {
    this.cer_id = localStorage.getItem('CisspCourseId');
    this.course_type = localStorage.getItem('course_type');
    await this.KnowassList();
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: true,
      practice: false,
      cat: false,
      datestring: false,
      knowques: false,
      knowresult: false,
      CATresult: false,
      CATQue: false,
      studentprofile: false,
      PracticeResult: false,
      Practiceques: false,
      resource: false,
      liveSupport: false
    };
    this.service.knnowlength = 0;
  }
  showReset(item) {
    this.ResetNamedata = item;
    this.resetResult = true;
  }
  async ViewSummery(item) {
    try {
      this.resetDatalist = [];
      await 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
            var cohort_id = localStorage.getItem('cohort_id');
            var user_id = localStorage.getItem('CisspUserId');
            await this.KnowledgeserviceService.getResetDataUser(
              parseInt(user_id),
              cohort_id,
              item.ass_id,
              token
            ).then(async (data) => {

              if (data[0].status == 200) {
                this.NoPrevRecordFound = false;
                var list = JSON.parse(<string>data[0].json);
                if (list.data.length > 0) {
                  await list.data.forEach((element) => {
                    element["percentage"] = Math.round((100 * element.correct) / item.total);
                    element['knowass_name'] = item.knowass_name;

                  });
                }
                else {
                  this.NoPrevRecordFound = true;
                }
                this.KnowledgeName = item.knowass_name;
                this.resetDatalist = list.data;
                this.ViewHistory = true;

              } else {
                if (data[0].status == 0) {
                  this.newerror = true;
                } else {
                  this.service.ShowError('Encountered server error!');
                }
              }

              await this.spinner.hide();
            });
          }
        });
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }
  }
  async GotoResult(item) {
    let total = parseInt(item.correct) + parseInt(item.incorrect) + parseInt(item.dknow);
    let currectPer = item.percentage;
    let incurrectPer = Math.round(item.incorrect * 100 / total)
    let donotKnow = 100 - (currectPer + incurrectPer)
    var dataPass = {
      ass_id: item.test_id,
      correct: item.correct,
      wrong: item.incorrect,
      dknow: item.dknow,
      currect_per: currectPer,
      incurrect_per: incurrectPer,
      dontknow_per: donotKnow,
      total: total,
    }
    localStorage.setItem('CisspknowAssId', item.test_id);
    localStorage.setItem('KnowAssData', JSON.stringify(item));
    localStorage.setItem('CisspknowRowNumber', item.RowNumber);

    var data = btoa(JSON.stringify(dataPass))
    await this.router.navigate([`/sidenav/knowledgeresult/${data}`]);
  }
  async KnowassList() {
    this.spinner.show()
    this.Knowasslist = [];
    this.newerror = false;
    let KnowAssList = this.sharedDataService.getKnowledgeAssessmentData()
    if (KnowAssList && KnowAssList.length > 0) {
      this.Knowasslist = KnowAssList;
      this.KnowassLen = this.Knowasslist.length;
      this.service.knnowlength = this.KnowassLen;
      this.service.title =
        "<p class='HeaderUser'>  <span> Knowledge Assessment (" +
        this.KnowassLen +
        ')</span></p>';
      if (this.KnowassLen > 0) {
        this.noFound = false;
      } else {
        this.noFound = true;
      }
      this.spinner.hide()
    } else {
      this.spinner.show()
      try {
        this.userid = localStorage.getItem('CisspUserId');
        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) {
                await this.spinner.hide();
                var list = JSON.parse(<string>data[0].json);
                if (list.data.length > 0) {
                  await list.data.forEach((element) => {
                    if (
                      element.c_date != undefined &&
                      element.c_date != '' &&
                      element.c_date != null
                    ) {
                      var CompletedDate = new Date(element.c_date);
                      element['CompletedDate'] = CompletedDate.toDateString();
                      element['label'] = 'Completed On';
                      element['Slabel'] = 'Completed';
                      element['dateset'] = CompletedDate.toDateString();
                      element['DueClassName'] = '';
                      element['DayGo'] = "";
                    }
                    else if (new Date(element.schedule[0].overdue_date) > new Date()) {
                      element['CompletedDate'] = '';
                      element['Slabel'] = 'In Progress';
                      element['label'] = 'Duedate';
                      element['DueClassName'] = '';
                      element['DayGo'] = "(Due in " + Math.ceil((new Date(element.schedule[0].overdue_date).getTime() - new Date().getTime()) / (1000 * 3600 * 24)) + ' days)';
                    } else {
                      element['CompletedDate'] = '';
                      element['Slabel'] = 'In Progress';
                      element['label'] = 'Overdue Date';
                      element['DueClassName'] = 'overduedate';
                      element['DayGo'] = "";
                    }
                    if (element.schedule.length > 0) {
                      if (element.total != 0) {
                        element['currectper'] = Math.round(
                          ((element.currect + element.wrong) * 100) /
                          element.total
                        );
                        element['totalcorrectper'] = Math.round(
                          ((element.currect) * 100) /
                          element.total
                        );
                      } else {
                        element['currectper'] = 0;
                        element['totalcorrectper'] = 0;
                      }
                      element['resultcount'] =
                        element.totalcorrectper + ' ' + (100 - element.totalcorrectper);
                      if (element.schedule[0] && element.schedule[0].due_date) {
                        var CurrentDate = new Date()

                        var startExamdate = new Date(
                          element.schedule[0].due_date
                        );
                        var StartExam_Dt = startExamdate.getTime() - CurrentDate.getTime();
                        var StartDateDay = Math.floor(StartExam_Dt / (1000 * 60 * 60 * 24)) + 1;
                        element['Ngclass'] = false;
                        if (!element.c_date) {
                          if (StartDateDay <= 0) {
                            if (
                              element.schedule[0] &&
                              element.schedule[0].overdue_date
                            ) {
                              var Enddate = new Date(element.schedule[0].overdue_date);
                              let dt = Enddate.getTime() - CurrentDate.getTime();
                              let days =
                                Math.floor(dt / (1000 * 60 * 60 * 24)) + 1;
                              var month = Enddate.toDateString();
                              if (days == 0) {
                                element['statusExam'] = '';
                                element['dateset'] = month;
                              } else if (days >= 0 && element.c_date == '') {
                                var monthnew = startExamdate.toDateString();

                                days = Math.abs(days);
                                element['statusExam'] = 'Due';
                                element['dateset'] = monthnew;
                              } else {
                                element['statusExam'] = 'Overdue';
                                element['dateset'] = month;
                              }
                            } else {
                              var monthnew = startExamdate.toDateString();
                              element['statusExam'] = 'Due';
                              element['dateset'] = monthnew;
                            }
                          } else {
                            element['Ngclass'] = true;
                            var month = startExamdate.toDateString();
                            element['label'] = 'Upcoming';
                            element['dateset'] = month;
                          }
                        }

                        this.Knowasslist.push(element);
                      }
                    }
                  });
                }
                if (this.Knowasslist.length > 0) {
                  this.Knowasslist.sort(
                    (a, b) =>
                      new Date(a.dateset).getTime() -
                      new Date(b.dateset).getTime()
                  );
                }
                this.sharedDataService.setKnowledgeAssessmentData(this.Knowasslist)

                this.KnowassLen = this.Knowasslist.length;
                this.service.knnowlength = this.KnowassLen;
                this.service.title =
                  "<p class='HeaderUser'>  <span> Knowledge Assessment (" +
                  this.KnowassLen +
                  ')</span></p>';
                if (this.KnowassLen > 0) {
                  this.noFound = false;
                } else {
                  this.noFound = true;
                }
              } else {
                this.spinner.hide()
                if (data[0].status == 0) {
                  this.newerror = true;
                } else {
                  this.service.ShowError('Encountered server error!');
                }
              }
            });
            await this.spinner.hide();
          }
        });
      } catch (e) {
        await this.spinner.hide();
      }
    }
  }

  StartAss(item, type) {
    this.userid = localStorage.getItem('CisspUserId');
    localStorage.setItem('CisspknowAssId', item.ass_id);
    localStorage.setItem('KnowAssData', JSON.stringify(item));
    localStorage.setItem('CisspknowRowNumber', "0");
    this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();

        this.router.navigate(['/login']);
      } else {
        var token = session
        this.service.testlogs_add(this.userid, item.ass_id, 'KA', type, token);
        this.router.navigate([`/sidenav/knowledgeQue`]);
      }
    });
  }
  async viewresult(item) {
    var dataPass = {
      ass_id: item.ass_id,
      correct: item.currect,
      wrong: item.wrong,
      dknow: item.dknow,
      currect_per: item.totalcorrectper,
      incurrect_per: Math.round(item.wrong * 100 / item.total),
      dontknow_per: Math.round(item.dknow * 100 / item.total),
      total: item.total,
    }
    localStorage.setItem('CisspknowAssId', item.ass_id);
    localStorage.setItem('KnowAssData', JSON.stringify(item));
    localStorage.setItem('CisspknowRowNumber', "0");

    var data = btoa(JSON.stringify(dataPass));
    await this.router.navigate([`/sidenav/knowledgeresult/${data}`]);
  }
  async reset() {
    await this.spinner.show();
    this.resetResult = false;
    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.ResetKnow(
          this.ResetNamedata.ass_id,
          this.ResetNamedata.user_id,
          token,
          cohort_id
        ).then(
          async (data) => {
            if (data[0].status == 200) {
              this.sharedDataService.setKnowledgeAssessmentData([])
              this.sharedDataService.setScheduleData([])
              this.sharedDataService.setSharedReviewGuideData([])
              await this.KnowassList();

              await this.service.ShowSuccess(
                this.ResetNamedata.knowass_name + 'reset successfully'
              );
            } else {
              await this.spinner.hide();
            }
          },
          (err) => {
            this.spinner.hide();
          }
        );
      }
    });
  }
  retuey() {
    window.location.reload();
  }
}