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 { SharedDataService } from 'src/app/services/SharedData/shared-data.service';
@Component({
  selector: 'app-practicetest',
  templateUrl: './practicetest.component.html',
  styleUrls: ['./practicetest.component.scss'],
})
export class PracticetestComponent implements OnInit {
  PaymentAccess: boolean = false;
  userid: any;
  data: any;
  name: any;
  practicetestlist = [];
  month: any;
  openModel: boolean = false;
  resetResult: boolean = false;
  Newpracticedata: any;
  ResetNamedata: any;
  noFound = false;
  newerror = false;
  resetDatalist = [];
  PracticeName = "";
  NoPrevRecordFound: boolean = false;
  ViewHistory: boolean = false;
  course_type: any;
  constructor(
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public ActiveRoute: ActivatedRoute,
    public router: Router,
    public PracticeserviceService: PracticeserviceService,
    public sharedDataService: SharedDataService
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
    this.userid = localStorage.getItem('CisspUserId');
    this.course_type = localStorage.getItem('course_type');
    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;
      }
    }
  }

  instarction = {
    FirstCheck: false,
    SecondCheck: false,
    ThirdCheck: false,
    ForthCheck: false,
  };
  showReset(item) {
    this.ResetNamedata = item;
    this.resetResult = true;
  }
  closeResult() {
    this.resetResult = false;
  }
  OpenCatModel(item) {
    this.instarction = {
      FirstCheck: false,
      SecondCheck: false,
      ThirdCheck: false,
      ForthCheck: false,
    };
    this.openModel = true;
    this.Newpracticedata = item;
  }

  CloseModel() {
    this.openModel = false;
  }

  async ngOnInit() {
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: true,
      studentprofile: false,
      cat: false,
      datestring: false,
      CATresult: false,
      knowques: false,
      knowresult: false,
      CATQue: false,
      PracticeResult: false,
      Practiceques: false,
      resource: false,
      liveSupport: false
    };
    await this.spinner.show();
    var data = localStorage.getItem('userdetails');
    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> Practice Test Summary </span></p>";
    }
    await this.listPracticetest();
    await this.CheckNofound();
  }
  async CheckNofound() {
    if (this.practicetestlist.length > 0) {
      this.noFound = false;
    } else {
      this.noFound = true;
    }
  }
  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.PracticeserviceService.getuserreportpracticetestAns(
              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';
                      element['DueClassName'] = '';
                      element['DayGo'] = '';
                    } else {
                      element['CompletedDate'] = '';
                      if (new Date(element.schedule[0].overdue_date) > new Date()) {
                        element['label'] = 'Due Date';
                        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['label'] = 'Overdue Date';
                        element['DueClassName'] = 'overduedate';
                        element['DayGo'] = '';
                      }

                    }
                    if (element.schedule.length > 0) {
                      if (element.schedule[0] && element.schedule[0].due_date) {
                        element['Perntage'] =
                          ((element.currect + element.wrong) * 100) /
                            element.total >
                            0
                            ? ((element.currect + element.wrong) * 100) /
                            element.total
                            : '0';
                        var circlecount =
                          ((element.currect + element.wrong) * 100) /
                            element.total >
                            0
                            ? ((element.currect + element.wrong) * 100) /
                            element.total
                            : 0;
                        element['CompletedPer'] =
                          ((element.currect) * 100) /
                            element.total >
                            0
                            ? Math.round(((element.currect) * 100) /
                              element.total)
                            : 0;
                        element['circlecount'] =
                          circlecount + ' ' + (100 - circlecount);
                        element['resultcount'] =
                          element.CompletedPer + ' ' + (100 - element.CompletedPer);
                        element['Perntage'] = Math.round(element['Perntage']);
                        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 (StartDateDay <= 0) {
                          var month = startExamdate.toDateString();
                          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;
                            if (days == 0) {
                              element['statusExam'] = '';
                            } else if (days > 0) {
                              days = Math.abs(days);
                              element['statusExam'] =
                                '(Due in ' + days + ' Days)';
                            } else {
                              element['statusExam'] =
                                '(Overdue in' + days + 'Days)';
                            }
                          } else {
                            element['statusExam'] = '';
                          }

                          element['dateset'] = month;
                        } else {
                          if (!element.c_date) {
                            element['Ngclass'] = true;

                            var month = startExamdate.toDateString();
                            element['label'] = 'Available on';
                          }
                          var month = startExamdate.toDateString();
                          element['dateset'] = month;
                        }

                        this.practicetestlist.push(element);
                      }
                    }
                  });
                  if (this.practicetestlist.length > 0) {
                    this.noFound = false;
                  } else {
                    this.noFound = true;
                  }
                }
                if (this.practicetestlist.length > 0) {
                  this.noFound = false;
                } else {
                  this.noFound = 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);
    }
  }
  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;
    }
  }
  StartPracticeTest() {
    var itemdaa = {
      id: this.Newpracticedata.test_id,
      type: this.Newpracticedata.test_type
        ? this.Newpracticedata.test_type
        : '',
    };
    var setdata = btoa(JSON.stringify(itemdaa));
    setdata = encodeURIComponent(setdata);
    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.Newpracticedata.test_id,
          'PRACTICE',
          'START',
          token
        );
      }
    });
    this.sharedDataService.setScheduleData([])
    this.router.navigate([`practicetestque/${setdata}`]);
  }
  resumetest(item) {
    var itemdaa = {
      id: item.test_id,
      type: item.test_type ? item.test_type : '',
    };
    var setdata = btoa(JSON.stringify(itemdaa));
    setdata = encodeURIComponent(setdata);
    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.test_id,
          'PRACTICE',
          'Resume',
          token
        );
      }
    });
    this.sharedDataService.setScheduleData([])
    this.router.navigate([`practicetestque/${setdata}`]);
  }
  viewresult(item) {
    var dataPass = {
      test_id: item.test_id,
      RowNumber: item.RowNumber,
      currect: item.currect,
      wrong: item.wrong,
      currect_per: item.CompletedPer,
      incurrect_per: 100 - item.CompletedPer,
      total: item.total,
    }
    var data = btoa(JSON.stringify(dataPass));
    data = encodeURIComponent(data);
    this.router.navigate([`sidenav/practicetestresult/${data}`]);
  }
  async reset() {
    this.resetResult = false;
    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');
        await this.PracticeserviceService.ResetTest(
          this.ResetNamedata.user_id,
          this.ResetNamedata.test_id,
          token,
          cohort_id
        ).then(
          async (data) => {
            if (data[0].status == 200) {
              await this.listPracticetest();
              this.sharedDataService.setScheduleData([])
              await this.service.ShowSuccess(
                this.ResetNamedata.practice_name + ' reset successfully'
              );
            } else {
              await this.spinner.hide();
            }
          },
          (err) => {
            this.spinner.hide();
          }
        );
      }
    });
  }
  retuey() {
    window.location.reload();
  }

  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');
            await this.PracticeserviceService.getResetDataUser(
              this.userid,
              cohort_id,
              item.test_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"] = (100 * element.correct) / item.total;
                    element["total"] = item.total;
                  });

                }
                else {
                  this.NoPrevRecordFound = true;
                }
                this.PracticeName = item.practice_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);
    }
  }

  GotoResult(item) {
    let incurrect_per = Math.round(100 - item.percentage);
    let currect = Math.round(item.percentage * item.total / 100);
    let wrong = item.total - currect;
    var dataPass = {
      test_id: item.test_id,
      RowNumber: item.RowNumber,
      currect: currect,
      wrong: wrong,
      currect_per: item.percentage,
      incurrect_per: incurrect_per,
      total: item.total,
    }
    var data = btoa(JSON.stringify(dataPass));
    data = encodeURIComponent(data);
    this.router.navigate([`sidenav/practicetestresult/${data}`]);
  }
}