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';
@Component({
  selector: 'app-cateexamtest',
  templateUrl: './cateexamtest.component.html',
  styleUrls: ['./cateexamtest.component.scss'],
})
export class CateexamtestComponent implements OnInit {
  PaymentAccess: boolean = false;
  userid: any;
  data: any;
  name: any;
  openModel: boolean = false;
  practicetestlist = [];
  nofound = false;
  CheckAccepet = false;
  ViewHistory: boolean = false;
  cateexamdata: any;
  instarction = {
    FirstCheck: false,
    SecondCheck: false,
    ThirdCheck: false,
    ForthCheck: false,
  };
  resetResult: boolean = false;
  noFound = false;
  course_type: any;
  constructor(
    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.service.headershow = true;
    this.service.SearchValue = true;

    this.userid = localStorage.getItem('CisspUserId');
    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.headerset = {
      dashboard: false,
      studyguuide: false,
      knowques: false,
      knowresult: false,
      knowledge: false,
      practice: false,
      cat: true,
      datestring: false,
      CATresult: false,
      studentprofile: false,
      CATQue: false,
      PracticeResult: false,
      Practiceques: false,
      resource: false,
      liveSupport: false
    };
  }

  ChnageTerm(check) {
    if (check == 'FirstCheck') {
      this.instarction.FirstCheck = !this.instarction.FirstCheck;
    }
    if (check == 'SecondCheck') {
      this.instarction.SecondCheck = !this.instarction.SecondCheck;
    }
    if (check == 'ThirdCheck') {
      this.instarction.ThirdCheck = !this.instarction.ThirdCheck;
    }
    if (check == 'ForthCheck') {
      this.instarction.ForthCheck = !this.instarction.ForthCheck;
    }
  }
  CheckClick() {
    this.CheckAccepet = !this.CheckAccepet;
  }
  startModel() {
    if (
      this.instarction.FirstCheck &&
      this.instarction.SecondCheck &&
      this.instarction.ThirdCheck &&
      this.instarction.ForthCheck
    ) {
      var data = btoa(JSON.stringify(this.cateexamdata.test_id));
      data = encodeURIComponent(data);
      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,
            this.cateexamdata.test_id,
            'CAT',
            'START',
            token
          );
        }
      });
      this.router.navigate([`cateexamtestque/${data}`]);
    } else {
      this.service.ShowError('Please accept term and condition.');
    }
  }
  showReset() {
    this.resetResult = true;
  }
  closeResult() {
    this.resetResult = false;
  }
  CloseModel() {
    this.openModel = false;
    this.CheckAccepet = false;
  }
  async ngOnInit() {
    await this.spinner.show();
    var data = localStorage.getItem('userdetails');
    this.course_type = localStorage.getItem('course_type');
    if (data != undefined || data != null || data != '') {
      this.data = JSON.parse(<string>data);
      this.name = this.data.aliasname ? this.data.aliasname : this.data.name;
      if (this.name != null) this.name = this.name.trim();
      this.service.title =
        "<p class='HeaderUser'>" +
        this.name +
        "'s <span > CAT EXAM Summary </span></p>";
    }
    await this.listPracticetest();
  }
  async listPracticetest() {
    this.practicetestlist = [];
    try {
      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.CatexamService.cateexamreportpracticetestAns(
              this.userid,
              cohort_id,
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                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';
                    } else {
                      element['CompletedDate'] = '';
                      element['label'] = 'In Process';
                    }
                    element['Ngclass'] = false;
                    if (element.schedule.length > 0) {
                      if (
                        element.schedule[0] &&
                        element.schedule[0].due_date
                      ) {
                        var startExamdate = new Date(
                          element.schedule[0].due_date
                        );

                        var CurrentDate = new Date();

                        var StartExam_Dt =
                          startExamdate.getTime() - CurrentDate.getTime();
                        var StartDateDay =
                          Math.floor(StartExam_Dt / (1000 * 60 * 60 * 24)) +
                          1;
                        if (StartDateDay <= 0) {
                          if (
                            element.schedule[0] &&
                            element.schedule[0].overdue_date
                          ) {
                            var circlecount =
                              ((element.currect + element.wrong) * 100) /
                                element.total >
                                0
                                ? ((element.currect + element.wrong) * 100) /
                                element.total
                                : 0;
                            element['circlecount'] =
                              circlecount + ' ' + (100 - circlecount);

                            if (element.percentage != 'NaN') {
                              element.percentage = Math.round(
                                element.percentage
                              );
                            } else {
                              element.percentage = 0;
                            }
                            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 = startExamdate.toDateString();
                            if (days >= 0) {
                              days = Math.abs(days);
                              element['statusExam'] =
                                '(Due in ' + days + ' Days)';
                              element['slable'] = "Due Date";
                            } else {
                              element['statusExam'] =
                                '(Overdue in' + days + 'Days)';
                              element['slable'] = "Overdue Date"
                            }
                            element['dateset'] = month;
                          } else {
                            var month = startExamdate.toDateString();
                            element['statusExam'] = '';
                            element['dateset'] = month;
                          }
                        } else {
                          element['Ngclass'] = true;
                          var month = startExamdate.toDateString();
                          element['label'] = 'Available on';
                          element['dateset'] = month;
                          element['slable'] = "Available on"
                        }
                        this.practicetestlist.push(element);
                      }
                    }
                  });
                }

                if (this.practicetestlist.length > 0) {
                  this.noFound = false;
                } else {
                  this.noFound = true;
                }
              }
              await this.spinner.hide();
            });
          }
        });
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }
    if (this.practicetestlist.length > 0) {
      this.noFound = false;
    } else {
      this.noFound = true;
    }
  }
  StartPracticeTest(item) {
    this.cateexamdata = item;
    this.instarction = {
      FirstCheck: false,
      SecondCheck: false,
      ThirdCheck: false,
      ForthCheck: false,
    };
    this.openModel = true;
  }
  viewresult(item) {
    var data = btoa(JSON.stringify(item.test_id));
    data = encodeURIComponent(data);
    this.router.navigate([`sidenav/cateexamtestresult/${data}`]);
  }
  retuey() {
    window.location.reload();
  }
  ngOnDestroy() { }
}