import {
  ChangeDetectorRef,
  Component,
  ElementRef,
  HostListener,
  Input,
  OnInit,
  ViewChild,
} from '@angular/core';
import { EventObject, FullCalendarOptions } from 'ngx-fullcalendar';
import { Calendar } from 'fullcalendar';
import { AuthserviceService } from '../../authservice.service';
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { Router } from '@angular/router';
import { ScheduleserviceService } from '../../services/Schedule/scheduleservice.service';
import { LoginflowService } from 'src/app/data/loginflow.service';
import { TZone } from 'moment-timezone-picker';
import * as momentZone from 'moment-timezone';
import { KnowledgeserviceService } from 'src/app/services/knowledge/knowledgeservice.service';
import { PracticeserviceService } from 'src/app/services/practice/practiceservice.service';
import { VgApiService } from '@videogular/ngx-videogular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { WebsocketService } from '../../services/websocket.service';
import {
  CalendarOptions,
  GoogleCalendar,
  ICalendar,
  OutlookCalendar,
  YahooCalendar,
} from 'datebook';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { VideoserviceService } from 'src/app/services/video/videoservice.service';
import { SharedDataService } from 'src/app/services/SharedData/shared-data.service';
import { environment } from 'src/environments/environment';


@Component({
  selector: 'app-schedule',
  templateUrl: './schedule.component.html',
  styleUrls: ['./schedule.component.scss'],
})
export class ScheduleComponent implements OnInit {
  math = Math;
  eventInnerHtml: any;
  EventLeft: any;
  EventTop: any;
  iSMoreEventPopup: boolean = false;
  SelectedEvent: any;
  VideoPopup: any;
  MindmapPopup: any;
  ExpiryDate: Date;
  HeaderStartDate: Date = new Date();
  main_title_id: any;
  PaymentAccess: boolean = false;
  options: FullCalendarOptions;
  events: EventObject[];
  ScheduleList = [];
  EventData = [];
  url: any;
  SelfCheckBox: boolean = true;
  UpdateSchedule: boolean = false;
  listView: boolean = true;
  weeklyView: boolean = false;
  listData = [];
  WeekData = [];
  MainWeekData = [];
  AssignMainWeekData = [];
  HomeworkMainWeekData = [];
  startdate: Date;
  enddate: Date;
  currentDate: Date = new Date();
  bkpScheduleList = [];
  calScheduleList = [];
  bkpSelfScheduleList = [];
  resetDatalist = [];
  study_date: any;
  newstudy_Date: any;
  flashcard_total_que: number = 1123;
  practice_total_que: number = 97;
  flashcard_app: number;
  flashcard_app_revision: number;
  practice_que_app: number;
  practice_que_app_revision: number;
  know_ass_revision: number;
  practice_test_revision: number;
  remainHours: number = 0;
  months = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sept',
    'Oct',
    'Nov',
    'Dec',
  ];
  ShowSuffienttime: boolean = false;
  ShowInvalidDate: boolean = false;
  misMatchSchedule: boolean = false;
  // custome: number = 0;
  custome: number = 1;
  ResetNamedata: any;
  resetResult = false;
  newerror = false;
  ViewHistory: boolean = false;
  NoPrevRecordFound: boolean = false;
  KnowledgeName = '';
  activestatus = 'Current Month';
  sun: number = 0;
  mon: number = 0;
  tues: number = 0;
  wed: number = 0;
  thurs: number = 0;
  fri: number = 0;
  sat: number = 0;
  hsun: number = 0;
  hmon: number = 0;
  htues: number = 0;
  hwed: number = 0;
  hthurs: number = 0;
  hfri: number = 0;
  hsat: number = 0;
  balance: number;
  sprint: number;
  insane: number;
  dis_balance: boolean = false;
  dis_sprint: boolean = false;
  dis_insane: boolean = false;
  IsSelfSchedule: boolean = false;
  IsSelfPacedClass: boolean = false;
  IsHybridClass: boolean = false;
  exam_date: any;
  self_schedule_id: any;
  aliasname: any;
  name: any;
  exam_name: any;
  exam_button: any;
  selected_schedule = {};
  isShowSchedule: boolean = false;
  isBaseShowSchedule: boolean = false;
  selected_BaseLine_schedule: any;
  changeDate: Boolean = false;
  GetDate: any;
  IsSelfScheduleDay: boolean = false;
  calKATime: number = 45;
  calPracticeTime: number = 45;
  calCatTime: number = 45;
  CalOtherTime: number = 45;
  noOfMin: number = 0;
  isNotSelfSchedualTime: number = 420;
  SelfScheduleTime: number = 0;
  ErrorSelfSchedule: number = 0;
  intervalTime: number = 4;
  Summery: boolean = false;
  timezone: any = JSON.parse(<string>localStorage.getItem('userdetails'))
    .user_time_zone
    ? JSON.parse(
      JSON.parse(<string>localStorage.getItem('userdetails')).user_time_zone
    ).nameValue
    : this.formatZone(momentZone.tz.guess(true)).nameValue;
  CustomeTitle: string = 'Create your own custom schedule';
  SelfPacedVideoPopup: boolean = false;
  SelfPacedVideoPopupInfo: any;
  api: VgApiService;
  VideoLink: any;
  playback: any;
  alreadyJoin: any;
  showJoinButton: boolean = false;
  isBefore15: boolean = false;
  nextLiveCall: any;
  upcomingLiveCall = [];
  upcomingCall: any;
  noEvent: boolean = true;
  playList = [];
  currentIndex = 0;
  currentItem: any;
  showControls: boolean = false;
  showSettingsPopup: boolean = false;
  showPlaybackPopup: boolean = false;
  showVideoQuality: boolean = false;
  activeSettings: boolean = false;
  playbackSpeedOptions: string[] = ['0.25', '0.5', '0.75', 'Normal', '1.25', '1.5', '1.75', '2.0'];
  selectedPlaybackSpeed: string = 'Normal';
  videoQualityOptions: string[] = []
  selectedVideoQuality: string = '1080p HD'
  selectedVideo: any;
  timer: any;
  dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  monthsNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
  dataSource: MatTableDataSource<supportList>;
  upcomingEventList: MatTableDataSource<upcomingEventDetail>;
  displayedColumns: string[] = ['name'];
  eventsDisplayedColumns: string[] = ['name']
  recordingsData = [];
  timezoneLive: any = JSON.parse(<string>localStorage.getItem('userdetails'))
    .user_time_zone
    ? JSON.parse(
      JSON.parse(<string>localStorage.getItem('userdetails')).user_time_zone
    )
    : this.formatZone(momentZone.tz.guess(true));
  @Input('pagination') pagination: boolean;
  @ViewChild(MatPaginator, { static: false }) set matPaginator(
    paginator: MatPaginator
  ) {
    if (this.pagination) {
      this.dataSource.paginator = paginator;
    }
  }
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  constructor(
    public socket: WebsocketService,
    public ScheduleserviceService: ScheduleserviceService,
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public router: Router,
    public LoginflowService: LoginflowService,
    public KnowledgeserviceService: KnowledgeserviceService,
    public PracticeserviceService: PracticeserviceService,
    public sanitizer: DomSanitizer,
    public changeDetect: ChangeDetectorRef,
    public videoService: VideoserviceService,
    public sharedDataService: SharedDataService,
    public EleRef: ElementRef
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
    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.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      knowques: false,
      knowresult: false,
      datestring: true,
      CATresult: false,
      CATQue: false,
      PracticeResult: false,
      Practiceques: false,
      studentprofile: false,
      resource: false,
      liveSupport: false,
    };
    momentZone.tz.setDefault(this.timezone);
    this.startdate = momentZone.parseZone(new Date()).local(true).toDate();
    this.enddate = momentZone.parseZone(new Date()).local(true).toDate();
    var course_type = localStorage.getItem('course_type');
    if (course_type != '' && course_type != null && course_type != 'hybrid')
      this.IsSelfPacedClass = true;
    else this.IsSelfPacedClass = false;
    if (course_type == 'hybrid') {
      this.IsHybridClass = true;
    }
  }
  @ViewChild('videoElement') videoElement!: ElementRef;
  @HostListener('document:click', ['$event'])
  onDocumentClick(event: Event): void {
    if (!this.videoElement?.nativeElement.contains(event.target)) {
      if (((!this.showPlaybackPopup && this.showVideoQuality) || (this.showPlaybackPopup && !this.showVideoQuality))) {
        this.toggleSettings();
      } else if (this.showSettingsPopup) {
        this.toggleSettings();
      }
    }
  }

  resetTimer() {
    this.showControls = true;
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.hideControls();
    }, 3000);
  }

  hideControls() {
    this.showControls = false;
  }

  toggleSettings() {
    if (!this.showSettingsPopup && (this.showPlaybackPopup || this.showVideoQuality)) {
      this.showSettingsPopup = false;
      this.showPlaybackPopup = false;
      this.showVideoQuality = false;
    } else {
      this.showSettingsPopup = !this.showSettingsPopup;
    }
    this.activeSettings = !this.activeSettings;
  }
  showoption(selectedOption: any) {
    if (selectedOption == 'PlaybackOptions') {
      setTimeout(() => {
        this.showPlaybackPopup = true;
      }, 10);
      this.showSettingsPopup = false;
    } else if (selectedOption == 'QualityOptions') {
      setTimeout(() => {
        this.showVideoQuality = true;
      }, 10);
      this.showSettingsPopup = false;
    }
  }
  backShowoption(selectedOption: any) {
    if (selectedOption == 'PlaybackOptions') {
      this.showPlaybackPopup = false;
      setTimeout(() => {
        this.showSettingsPopup = true;
      }, 10);
    } else if (selectedOption == 'QualityOptions') {
      this.showVideoQuality = false;
      setTimeout(() => {
        this.showSettingsPopup = true;
      }, 10);
    }
  }
  setPlaybackSpeed(speed: string) {
    this.api.playbackRate = speed == 'Normal' ? '1.0' : speed;
    this.selectedPlaybackSpeed = speed;
  }
  async setVideoQuality(quality: string) {
    this.selectedVideoQuality = quality;
    var audi = document.getElementsByTagName('video');
    var currentTime = audi[0].currentTime
    await this.changetranscode(this.selectedVideo)
    var player = this.EleRef.nativeElement.querySelector('video');
    await player.load();
    setTimeout(() => {
      var vid = document.getElementsByTagName('video');
      vid[0].currentTime = currentTime
      this.api.playbackRate = this.selectedPlaybackSpeed == 'Normal' ? '1.0' : this.selectedPlaybackSpeed;
    }, 1000);
  }
  async changetranscode(item) {
    if (this.selectedVideoQuality == '720p' && item.download_url_720p) {
      this.VideoLink = item.download_url_720p;
    } else if (this.selectedVideoQuality == '480p' && item.download_url_480p) {
      this.VideoLink = item.download_url_480p;
    } else if (this.selectedVideoQuality == '360p' && item.download_url_360p) {
      this.VideoLink = item.download_url_360p;
    } else if (this.selectedVideoQuality == '240p' && item.download_url_240p) {
      this.VideoLink = item.download_url_240p;
    } else if (this.selectedVideoQuality == '144p' && item.download_url_144p) {
      this.VideoLink = item.download_url_144p;
    } else {
      this.VideoLink = item.download_url
    }
  }

  List() {
    this.listView = true;
    this.weeklyView = false;
  }
  async Weekly() {
    this.listView = false;
    this.weeklyView = true;
    this.MainWeekData = [];
    this.AssignMainWeekData = [];
    this.HomeworkMainWeekData = [];
    await this.createWeekly();
    var dataweek = [];
    await this.MainWeekData.forEach((element) => {
      var filterdata = [];
      if (element && element.length > 0) {
        filterdata = element.filter(
          (item) => item.ScheduleData && item.ScheduleData.length > 0
        );
      }
      if (filterdata && filterdata.length > 0) {
        dataweek.push(element);
      }
    });
    this.MainWeekData = dataweek;
    this.HomeworkMainWeekData = this.MainWeekData.map((element) => {
      let home = 0;
      element = element.map((el) => {
        let p = Object.assign({}, el);
        el = Object.assign({}, el);
        var index = p.ScheduleData.findIndex(
          (item) =>
            item.type_id == this.selected_BaseLine_schedule.id &&
            item.type == this.selected_BaseLine_schedule.type
        );
        if (index != -1) {
          p.ScheduleData.splice(index, 1);
        }

        el.ScheduleData = p.ScheduleData.filter(
          (x) =>
            (x.homework == 0 || x.homework == null) &&
            (x.type != 'title' ||
              x.title_type == 'Flashcard App' ||
              x.title_type == 'Practice Question App')
        );
        el.HomeworkData = p.ScheduleData.filter(
          (x) =>
            x.homework == 1 &&
            (x.type != 'title' ||
              x.title_type == 'Flashcard App' ||
              x.title_type == 'Practice Question App')
        );
        if (el.HomeworkData.length > 0 && home == 0) {
          home = 1;
        }

        return el;
      });
      element.home = home;

      return element;
    });
    if (!this.IsSelfPacedClass) {
      setTimeout(() => {
        let bkpeventData = [];
        let bkpHomeventData = [];
        let number = 1;
        for (let i = 0; i < this.HomeworkMainWeekData.length; i++) {
          let eventData = [];
          let HomeeventData = [];
          for (let j = 0; j < this.HomeworkMainWeekData[i].length; j++) {
            if (this.HomeworkMainWeekData[i][j].ScheduleData.length > 0) {
              let old_date = null;
              let old_time = 0;
              let old_hour = null;
              let old_minute = null;
              let old_second = null;
              let Event_old_hour = null;
              let Event_old_minute = null;
              let Event_old_second = null;
              for (
                let a = 0;
                a < this.HomeworkMainWeekData[i][j].ScheduleData.length;
                a++
              ) {
                let due_date = null;
                let end_due_date = null;

                let CheckDate = this.auth.ConvertFormatDbDateTime(
                  this.HomeworkMainWeekData[i][j].ScheduleData[a].due_date,
                  this.timezone
                );
                if (this.IsSelfPacedClass) {
                  if (
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].type !=
                    'Events'
                  ) {
                    if (
                      new Date(old_date).toDateString() !=
                      new Date(CheckDate).toDateString()
                    ) {
                      old_time = 6;
                      old_date = this.auth.ConvertFormatDbDateTime(
                        this.HomeworkMainWeekData[i][j].ScheduleData[a]
                          .due_date,
                        this.timezone
                      );

                      if (
                        this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                        'VideoLesson' ||
                        this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                        'MindMap'
                      ) {
                        due_date = new Date(
                          new Date(old_date).setHours(0, 0, 0)
                        );
                        let minutes = this.HomeworkMainWeekData[i][
                          j
                        ].ScheduleData[a].videolength
                          .split(':')[0]
                          .replace('m', '');
                        let seconds = this.HomeworkMainWeekData[i][
                          j
                        ].ScheduleData[a].videolength
                          .split(':')[1]
                          .replace('s', '');
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            0,
                            parseInt(minutes),
                            parseInt(seconds)
                          )
                        );
                        old_hour = new Date(end_due_date).getHours();
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second =
                          new Date(end_due_date).getSeconds() +
                          parseInt(seconds) * this.intervalTime;
                      } else {
                        due_date = new Date(
                          new Date(old_date).setHours(0, 0, 0)
                        );
                        let hours =
                          this.HomeworkMainWeekData[i][j].ScheduleData[
                            a
                          ].time.split(':')[0];
                        let minutes =
                          this.HomeworkMainWeekData[i][j].ScheduleData[
                            a
                          ].time.split(':')[1];
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            parseInt(hours),
                            parseInt(minutes)
                          )
                        );
                        old_hour =
                          new Date(end_due_date).getHours() +
                          parseInt(hours) * this.intervalTime;
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second = new Date(end_due_date).getSeconds();
                      }
                    } else {
                      old_date = this.auth.ConvertFormatDbDateTime(
                        this.HomeworkMainWeekData[i][j].ScheduleData[a]
                          .due_date,
                        this.timezone
                      );

                      if (
                        this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                        'VideoLesson' ||
                        this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                        'MindMap'
                      ) {
                        due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour,
                            old_minute,
                            old_second
                          )
                        );
                        let minutes = this.HomeworkMainWeekData[i][
                          j
                        ].ScheduleData[a].videolength
                          .split(':')[0]
                          .replace('m', '');
                        let seconds = this.HomeworkMainWeekData[i][
                          j
                        ].ScheduleData[a].videolength
                          .split(':')[1]
                          .replace('s', '');
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour,
                            old_minute + parseInt(minutes),
                            old_second + parseInt(seconds)
                          )
                        );
                        old_hour = new Date(end_due_date).getHours();
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second =
                          new Date(end_due_date).getSeconds() +
                          parseInt(seconds) * this.intervalTime;
                      } else {
                        due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour,
                            old_minute,
                            old_second
                          )
                        );
                        let hours =
                          this.HomeworkMainWeekData[i][j].ScheduleData[
                            a
                          ].time.split(':')[0];
                        let minutes =
                          this.HomeworkMainWeekData[i][j].ScheduleData[
                            a
                          ].time.split(':')[1];
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour + parseInt(hours),
                            old_minute + parseInt(minutes)
                          )
                        );
                        old_hour =
                          new Date(end_due_date).getHours() +
                          parseInt(hours) * this.intervalTime;
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second = new Date(end_due_date).getSeconds();
                      }
                    }
                  } else {
                    old_date = this.auth.ConvertFormatDbDateTime(
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].due_date,
                      this.timezone
                    );
                    Event_old_hour = new Date(old_date).getHours();
                    Event_old_minute = new Date(old_date).getMinutes();
                    Event_old_second = new Date(old_date).getSeconds();
                    due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute,
                        Event_old_second
                      )
                    );
                    end_due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute +
                        parseInt(
                          this.HomeworkMainWeekData[i][j].ScheduleData[a]
                            .event_minutes
                        ),
                        Event_old_second
                      )
                    );
                  }
                } else {
                  if (
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].type !=
                    'Events'
                  ) {
                    old_date = this.auth.ConvertFormatDbDateTime(
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].due_date,
                      this.timezone
                    );
                    old_hour = new Date(old_date).getHours();
                    old_minute = new Date(old_date).getMinutes();
                    old_second = new Date(old_date).getSeconds();
                    if (
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                      'VideoLesson' ||
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                      'MindMap'
                    ) {
                      due_date = new Date(
                        new Date(old_date).setHours(
                          old_hour,
                          old_minute,
                          old_second
                        )
                      );
                      let minutes = this.HomeworkMainWeekData[i][
                        j
                      ].ScheduleData[a].videolength
                        .split(':')[0]
                        .replace('m', '');
                      let seconds = this.HomeworkMainWeekData[i][
                        j
                      ].ScheduleData[a].videolength
                        .split(':')[1]
                        .replace('s', '');
                      end_due_date = new Date(
                        new Date(old_date).setHours(
                          old_hour,
                          old_minute + parseInt(minutes),
                          old_second + parseInt(seconds)
                        )
                      );
                    } else {
                      due_date = new Date(
                        new Date(old_date).setHours(
                          old_hour,
                          old_minute,
                          old_second
                        )
                      );
                      let hours =
                        this.HomeworkMainWeekData[i][j].ScheduleData[
                          a
                        ].time.split(':')[0];
                      let minutes =
                        this.HomeworkMainWeekData[i][j].ScheduleData[
                          a
                        ].time.split(':')[1];
                      end_due_date = new Date(
                        new Date(old_date).setHours(
                          old_hour + parseInt(hours),
                          old_minute + parseInt(minutes)
                        )
                      );
                    }
                  } else {
                    (old_date =
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].due_date),
                      this.timezone;
                    Event_old_hour = new Date(old_date).getHours();
                    Event_old_minute = new Date(old_date).getMinutes();
                    Event_old_second = new Date(old_date).getSeconds();
                    due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute,
                        Event_old_second
                      )
                    );
                    end_due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute +
                        parseInt(
                          this.HomeworkMainWeekData[i][j].ScheduleData[a]
                            .event_minutes
                        ),
                        Event_old_second
                      )
                    );
                  }
                }

                let flt = bkpeventData.filter(
                  (x) =>
                    x.id ==
                    (this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                      'Events'
                      ? this.HomeworkMainWeekData[i][j].ScheduleData[a].id
                      : this.HomeworkMainWeekData[i][j].ScheduleData[a]
                        .type_id) &&
                    x.className ==
                    (this.HomeworkMainWeekData[i][j].ScheduleData[a].status ==
                      'Not Started'
                      ? 'regular'
                      : this.HomeworkMainWeekData[i][j].ScheduleData[a]
                        .status) &&
                    x.title ==
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].examname +
                    ' $' +
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].type &&
                    x.start ==
                    this.auth.ConvertFormatDbDateTime(
                      due_date,
                      this.timezone
                    ) &&
                    x.end ==
                    this.auth.ConvertFormatDbDateTime(
                      end_due_date,
                      this.timezone
                    )
                );
                bkpeventData.push({
                  id:
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                      'Events'
                      ? this.HomeworkMainWeekData[i][j].ScheduleData[a].id
                      : this.HomeworkMainWeekData[i][j].ScheduleData[a].type_id,
                  className:
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].status ==
                      'Not Started'
                      ? 'regular'
                      : this.HomeworkMainWeekData[i][j].ScheduleData[a].status,
                  title:
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].examname +
                    ' $' +
                    this.HomeworkMainWeekData[i][j].ScheduleData[a].type,
                  start: this.auth.ConvertFormatDbDateTime(
                    due_date,
                    this.timezone
                  ),
                  end: this.auth.ConvertFormatDbDateTime(
                    end_due_date,
                    this.timezone
                  ),
                  extendedProps: {
                    event_data: this.HomeworkMainWeekData[i][j].ScheduleData[a],
                  },
                });
                if (flt.length <= 0) {
                  eventData.push({
                    id:
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].type ==
                        'Events'
                        ? this.HomeworkMainWeekData[i][j].ScheduleData[a].id
                        : this.HomeworkMainWeekData[i][j].ScheduleData[a]
                          .type_id,
                    className:
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].status ==
                        'Not Started'
                        ? 'regular'
                        : this.HomeworkMainWeekData[i][j].ScheduleData[a]
                          .status,
                    title:
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].examname +
                      ' $' +
                      this.HomeworkMainWeekData[i][j].ScheduleData[a].type,
                    start: this.auth.ConvertFormatDbDateTime(
                      due_date,
                      this.timezone
                    ),
                    end: this.auth.ConvertFormatDbDateTime(
                      end_due_date,
                      this.timezone
                    ),
                    extendedProps: {
                      event_data:
                        this.HomeworkMainWeekData[i][j].ScheduleData[a],
                    },
                  });
                }
              }
            }
            if (this.HomeworkMainWeekData[i][j].HomeworkData.length > 0) {
              let old_date = null;
              let old_time = 0;
              let old_hour = null;
              let old_minute = null;
              let old_second = null;
              let Event_old_hour = null;
              let Event_old_minute = null;
              let Event_old_second = null;
              for (
                let a = 0;
                a < this.HomeworkMainWeekData[i][j].HomeworkData.length;
                a++
              ) {
                let due_date = null;
                let end_due_date = null;

                let CheckDate = this.auth.ConvertFormatDbDateTime(
                  this.HomeworkMainWeekData[i][j].HomeworkData[a].due_date,
                  this.timezone
                );
                if (this.IsSelfPacedClass) {
                  if (
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].type !=
                    'Events'
                  ) {
                    if (
                      new Date(old_date).toDateString() !=
                      new Date(CheckDate).toDateString()
                    ) {
                      old_time = 6;
                      old_date = this.auth.ConvertFormatDbDateTime(
                        this.HomeworkMainWeekData[i][j].HomeworkData[a]
                          .due_date,
                        this.timezone
                      );

                      if (
                        this.HomeworkMainWeekData[i][j].HomeworkData[a].type ==
                        'VideoLesson' ||
                        this.HomeworkMainWeekData[i][j].HomeworkData[a].type ==
                        'MindMap'
                      ) {
                        due_date = new Date(
                          new Date(old_date).setHours(0, 0, 0)
                        );
                        let minutes = this.HomeworkMainWeekData[i][
                          j
                        ].HomeworkData[a].videolength
                          .split(':')[0]
                          .replace('m', '');
                        let seconds = this.HomeworkMainWeekData[i][
                          j
                        ].HomeworkData[a].videolength
                          .split(':')[1]
                          .replace('s', '');
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            0,
                            parseInt(minutes),
                            parseInt(seconds)
                          )
                        );
                        old_hour = new Date(end_due_date).getHours();
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second =
                          new Date(end_due_date).getSeconds() +
                          parseInt(seconds) * this.intervalTime;
                      } else {
                        due_date = new Date(
                          new Date(old_date).setHours(0, 0, 0)
                        );
                        let hours =
                          this.HomeworkMainWeekData[i][j].HomeworkData[
                            a
                          ].time.split(':')[0];
                        let minutes =
                          this.HomeworkMainWeekData[i][j].HomeworkData[
                            a
                          ].time.split(':')[1];
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            parseInt(hours),
                            parseInt(minutes)
                          )
                        );
                        old_hour =
                          new Date(end_due_date).getHours() +
                          parseInt(hours) * this.intervalTime;
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second = new Date(end_due_date).getSeconds();
                      }
                    } else {
                      old_date = this.auth.ConvertFormatDbDateTime(
                        this.HomeworkMainWeekData[i][j].HomeworkData[a]
                          .due_date,
                        this.timezone
                      );
                      if (
                        this.HomeworkMainWeekData[i][j].HomeworkData[a].type ==
                        'VideoLesson' ||
                        this.HomeworkMainWeekData[i][j].HomeworkData[a].type ==
                        'MindMap'
                      ) {
                        due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour,
                            old_minute,
                            old_second
                          )
                        );
                        let minutes = this.HomeworkMainWeekData[i][
                          j
                        ].HomeworkData[a].videolength
                          .split(':')[0]
                          .replace('m', '');
                        let seconds = this.HomeworkMainWeekData[i][
                          j
                        ].HomeworkData[a].videolength
                          .split(':')[1]
                          .replace('s', '');
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour,
                            old_minute + parseInt(minutes),
                            old_second + parseInt(seconds)
                          )
                        );
                        old_hour = new Date(end_due_date).getHours();
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second =
                          new Date(end_due_date).getSeconds() +
                          parseInt(seconds) * this.intervalTime;
                      } else {
                        due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour,
                            old_minute,
                            old_second
                          )
                        );
                        let hours =
                          this.HomeworkMainWeekData[i][j].HomeworkData[
                            a
                          ].time.split(':')[0];
                        let minutes =
                          this.HomeworkMainWeekData[i][j].HomeworkData[
                            a
                          ].time.split(':')[1];
                        end_due_date = new Date(
                          new Date(old_date).setHours(
                            old_hour + parseInt(hours),
                            old_minute + parseInt(minutes)
                          )
                        );
                        old_hour =
                          new Date(end_due_date).getHours() +
                          parseInt(hours) * this.intervalTime;
                        old_minute =
                          new Date(end_due_date).getMinutes() +
                          parseInt(minutes) * this.intervalTime;
                        old_second = new Date(end_due_date).getSeconds();
                      }
                    }
                  } else {
                    old_date = this.auth.ConvertFormatDbDateTime(
                      this.HomeworkMainWeekData[i][j].HomeworkData[a].due_date,
                      this.timezone
                    );
                    Event_old_hour = new Date(old_date).getHours();
                    Event_old_minute = new Date(old_date).getMinutes();
                    Event_old_second = new Date(old_date).getSeconds();
                    due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute,
                        Event_old_second
                      )
                    );
                    end_due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute +
                        parseInt(
                          this.HomeworkMainWeekData[i][j].HomeworkData[a]
                            .event_minutes
                        ),
                        Event_old_second
                      )
                    );
                  }
                } else {
                  if (
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].type !=
                    'Events'
                  ) {
                    if (
                      new Date(old_date).toDateString() !=
                      new Date(CheckDate).toDateString()
                    ) {
                      old_time = 6;
                      old_date = this.auth.ConvertFormatDbDateTime(
                        this.HomeworkMainWeekData[i][j].HomeworkData[a]
                          .due_date,
                        this.timezone
                      );
                      due_date = new Date(new Date(old_date).setHours(0, 5, 0));
                      end_due_date = new Date(
                        new Date(old_date).setHours(1, 50, 0)
                      );
                      old_hour = new Date(end_due_date).getHours();
                      old_minute = new Date(end_due_date).getMinutes() + 10;
                      old_second = new Date(end_due_date).getSeconds();
                    } else {
                      old_date = this.auth.ConvertFormatDbDateTime(
                        this.HomeworkMainWeekData[i][j].HomeworkData[a]
                          .due_date,
                        this.timezone
                      );
                      due_date = new Date(
                        new Date(old_date).setHours(
                          old_hour,
                          old_minute + 5,
                          old_second
                        )
                      );
                      end_due_date = new Date(
                        new Date(old_date).setHours(
                          old_hour + 1,
                          old_minute + 50
                        )
                      );
                      old_hour = new Date(end_due_date).getHours();
                      old_minute = new Date(end_due_date).getMinutes() + 10;
                      old_second = new Date(end_due_date).getSeconds();
                    }
                  } else {
                    old_date = this.auth.ConvertFormatDbDateTime(
                      this.HomeworkMainWeekData[i][j].HomeworkData[a].due_date,
                      this.timezone
                    );
                    Event_old_hour = new Date(old_date).getHours();
                    Event_old_minute = new Date(old_date).getMinutes();
                    Event_old_second = new Date(old_date).getSeconds();
                    due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute,
                        Event_old_second
                      )
                    );
                    end_due_date = new Date(
                      new Date(old_date).setHours(
                        Event_old_hour,
                        Event_old_minute +
                        parseInt(
                          this.HomeworkMainWeekData[i][j].HomeworkData[a]
                            .event_minutes
                        ),
                        Event_old_second
                      )
                    );
                  }
                }
                let flt = bkpHomeventData.filter(
                  (x) =>
                    x.id ==
                    (this.HomeworkMainWeekData[i][j].HomeworkData[a].type ==
                      'Events'
                      ? this.HomeworkMainWeekData[i][j].HomeworkData[a].id
                      : this.HomeworkMainWeekData[i][j].HomeworkData[a]
                        .type_id) &&
                    x.className ==
                    (this.HomeworkMainWeekData[i][j].HomeworkData[a].status ==
                      'Not Started'
                      ? 'regular'
                      : this.HomeworkMainWeekData[i][j].HomeworkData[a]
                        .status) &&
                    x.title ==
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].examname +
                    ' $' +
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].type &&
                    x.start ==
                    this.auth.ConvertFormatDbDateTime(
                      due_date,
                      this.timezone
                    ) &&
                    x.end ==
                    this.auth.ConvertFormatDbDateTime(
                      end_due_date,
                      this.timezone
                    )
                );
                bkpHomeventData.push({
                  id:
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].type ==
                      'Events'
                      ? this.HomeworkMainWeekData[i][j].HomeworkData[a].id
                      : this.HomeworkMainWeekData[i][j].HomeworkData[a].type_id,
                  className:
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].status ==
                      'Not Started'
                      ? 'regular'
                      : this.HomeworkMainWeekData[i][j].HomeworkData[a].status,
                  title:
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].examname +
                    ' $' +
                    this.HomeworkMainWeekData[i][j].HomeworkData[a].type,
                  start: this.auth.ConvertFormatDbDateTime(
                    due_date,
                    this.timezone
                  ),
                  end: this.auth.ConvertFormatDbDateTime(
                    end_due_date,
                    this.timezone
                  ),
                  extendedProps: {
                    event_data: this.HomeworkMainWeekData[i][j].HomeworkData[a],
                  },
                });

                if (flt.length <= 0) {
                  HomeeventData.push({
                    id:
                      this.HomeworkMainWeekData[i][j].HomeworkData[a].type ==
                        'Events'
                        ? this.HomeworkMainWeekData[i][j].HomeworkData[a].id
                        : this.HomeworkMainWeekData[i][j].HomeworkData[a]
                          .type_id,
                    className:
                      this.HomeworkMainWeekData[i][j].HomeworkData[a].status ==
                        'Not Started'
                        ? 'regular'
                        : this.HomeworkMainWeekData[i][j].HomeworkData[a]
                          .status,
                    title:
                      this.HomeworkMainWeekData[i][j].HomeworkData[a].examname +
                      ' $' +
                      this.HomeworkMainWeekData[i][j].HomeworkData[a].type,
                    start: this.auth.ConvertFormatDbDateTime(
                      due_date,
                      this.timezone
                    ),
                    end: this.auth.ConvertFormatDbDateTime(
                      end_due_date,
                      this.timezone
                    ),
                    extendedProps: {
                      event_data:
                        this.HomeworkMainWeekData[i][j].HomeworkData[a],
                    },
                  });
                }
              }
            }
          }

          let days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat'];
          if (eventData.length > 0) {
            let dateArray = [];
            let dateEndArray = [];
            let changeDate = false;
            eventData.forEach((element) => {
              if (
                new Date(element.start).toDateString() <
                new Date(element.end).toDateString()
              ) {
                changeDate = true;
              }
              dateArray.push(new Date(element.start).getHours());
              dateArray.push(new Date(element.end).getHours());
              dateEndArray.push(new Date(element.start).getHours());
              dateEndArray.push(new Date(element.end).getHours());
            });
            var hour = dateArray.reduce(function (a, b) {
              return a < b ? a : b;
            });
            var endhour = dateEndArray.reduce(function (a, b) {
              return a > b ? a : b;
            });
            if (changeDate) {
              hour = 0;
              endhour = 24;
              changeDate = false;
            }
            let defaultDate =
              eventData.length > 1
                ? new Date(eventData[1].start)
                : new Date(eventData[0].start);
            let calendarElHome: HTMLElement = document.getElementById(
              'calendar' + (i + 1)
            );
            let me = this;
            new Calendar(calendarElHome, {
              plugins: [],
              defaultView: window.innerWidth > 768 ? 'agendaWeek' : 'agendaDay',
              defaultDate: defaultDate,
              showNonCurrentDates: true,
              editable: false,
              eventLimit: 2,
              events: eventData,
              allDaySlot: false,
              eventOverlap: false,
              columnHeaderFormat: {
                day: 'numeric',
                weekday: 'short',
                month: 'short',
              },
              displayEventTime: true,
              eventTimeFormat: {
                hour: 'numeric',
                minute: '2-digit',
                meridiem: 'short',
              },
              buttonText: {
                today: 'Today',
              },
              header: false,

              slotDuration: {
                minutes: 15,
              },
              slotLabelInterval: {
                hours: 1,
              },
              minTime: { hour: hour },
              maxTime: {
                hour: endhour == 24 ? endhour : endhour + 1,
                minutes: endhour == 24 ? 0 : 30,
              },
              eventClick: function (info) {
                me.eventInnerHtml = me.sanitizer.bypassSecurityTrustHtml(
                  info.el.innerHTML
                );
                me.iSMoreEventPopup = true;
                me.EventLeft = info.jsEvent.clientX;
                me.EventTop = info.jsEvent.clientY;
                me.SelectedEvent = info.event.extendedProps.event_data;
              },
              columnHeaderHtml: function (params) {
                var fulldate = new Date(params.toString());
                let dt = fulldate.getUTCDate();
                let mon = me.months[fulldate.getUTCMonth()];
                let current_date = me.auth.ConvertDateDDFormat(
                  new Date(),
                  me.timezone,
                  'DD'
                );
                let current_month = me.auth.ConvertDateDDFormat(
                  new Date(),
                  me.timezone,
                  'MM'
                );
                let cls = '';
                if (parseInt(current_date) == dt && mon == me.months[parseInt(current_month) - 1]) {
                  cls = 'active';
                }
                let day = days[fulldate.getUTCDay()];
                let year = fulldate.getUTCFullYear().toString().substr(2, 3);
                let res = `<div class="date-head"><span class="main-date ${cls}">${dt}</span>
                  <div class="date-month">
                    <span class="${cls}">${day}</span>
                    <span  class="${cls}">${mon}'${year}</span>
                  </div></div>`;
                return res;
              },
              eventRender: function (info) {
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$MindMap',
                  '<svg width="22" height="20" viewBox="0 0 22 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M9.89476 0.375206C10.2885 0.170633 10.7323 0.0410951 11.2294 0.00825915L11.4823 0C12.1668 0 12.7743 0.184647 13.2528 0.464229L13.28 0.480941L13.3201 0.474429C13.8633 0.397683 14.4215 0.466498 14.9211 0.706172L15.1056 0.804108C15.3682 0.958994 15.4758 1.02641 15.6146 1.16777L15.6969 1.25645L15.7645 1.24925C17.6013 1.0833 19.5332 2.3416 19.8923 4.19938L19.9146 4.3391L20.0302 4.42896C20.8658 5.12651 21.2613 6.30579 21.0349 7.36596L21.0217 7.41564L21.0402 7.44401C21.2014 7.55084 21.3121 7.72594 21.3336 7.92536C21.6958 8.58395 21.9243 9.29109 21.9821 10.1113C22.1036 11.8158 21.5959 13.0272 20.7795 13.7618L20.7376 13.7973L20.7248 14.0144C20.6843 14.4155 20.5643 14.83 20.3416 15.244L20.2216 15.4509C19.7134 16.2682 18.93 16.6867 18.0564 16.7408C17.9796 16.7455 17.9036 16.7475 17.8285 16.747L17.7411 16.7428C17.7242 16.75 17.707 16.7565 17.6895 16.7623L17.66 16.7991C17.1563 17.3789 16.3703 17.721 15.4089 17.9074L15.2002 17.945C14.8528 18.0031 14.4937 18.0395 14.1159 18.0606L13.9556 18.8536C13.8352 19.4676 13.3272 19.9341 12.7034 19.9936L12.568 20H11.7998C11.1538 20 10.5965 19.5625 10.4338 18.9486C10.2237 18.1652 9.91752 17.195 9.69557 16.5744C9.60245 16.4821 9.53567 16.3613 9.51034 16.2225C9.49788 16.1541 9.48617 16.0866 9.47522 16.0197C9.45854 15.9869 9.44491 15.9651 9.43481 15.9557C9.26814 15.8001 9.05269 15.7177 8.39742 15.5654L8.04114 15.4783C7.19044 15.2517 6.52719 14.9194 5.97064 14.3424C6.00795 14.3812 5.33067 13.6438 5.11846 13.4403L4.93371 13.2707C4.50545 12.8953 4.09448 12.6624 3.64782 12.5615C2.18597 12.2328 1.39635 11.4198 1.20379 10.4731L1.20031 10.4524L1.11956 10.3972C0.974895 10.2897 0.836952 10.1626 0.708256 10.015L0.582735 9.86044C-0.129563 8.92782 -0.215357 7.38097 0.47255 5.96296C0.781601 5.33105 1.19484 4.8439 1.64185 4.48544L1.67901 4.45645L1.70986 4.34066C1.82042 3.97769 2.03854 3.62199 2.36634 3.29946L2.51354 3.16333C2.80049 2.91224 3.11313 2.75465 3.44268 2.65986L3.51438 2.64115L3.56002 2.57977C3.83008 2.22805 4.20156 1.90535 4.68536 1.64518L4.89961 1.53761C5.51069 1.25162 6.14012 1.16636 6.7467 1.2043L6.77467 1.20645L6.89742 1.08084C7.12338 0.863657 7.39032 0.67749 7.70711 0.537493L7.90323 0.459157C8.5354 0.234315 9.13565 0.235922 9.68341 0.371026L9.82921 0.411554L9.89476 0.375206ZM10.7685 15.7231C10.5432 14.2905 10.749 13.5679 11.2347 13.3834L11.3236 13.342C11.6054 13.1843 11.7369 12.8395 11.619 12.5281C11.4894 12.1856 11.1072 12.0132 10.7653 12.1431C9.87017 12.4831 9.42343 13.2739 9.36515 14.4477C9.25035 14.4111 9.13353 14.3792 9.01553 14.3494L8.60154 14.2511C7.98939 14.1087 7.37723 13.8917 6.92438 13.4222C6.84217 13.3367 6.75382 13.2396 6.65858 13.135C6.55807 13.0246 6.44989 12.9058 6.33318 12.7832C7.34978 12.587 8.08811 11.8348 8.47052 10.5268C8.5733 10.1752 8.37216 9.80676 8.02127 9.70379C7.67038 9.60083 7.30261 9.80233 7.19983 10.1539C6.76429 11.6436 5.83176 11.9172 3.94099 10.9754C3.7108 10.8608 3.44603 10.8928 3.25252 11.0359C2.37712 10.6065 2.45439 9.92748 2.53015 9.65066C2.54652 9.59169 2.50506 9.53495 2.44613 9.5305C2.26718 9.52049 1.93 9.44484 1.63429 9.05433C1.33094 8.65715 1.11051 7.68255 1.66157 6.54663C2.06422 5.72334 2.7102 5.33506 2.94153 5.21824C2.98409 5.19599 3.00373 5.14482 2.98518 5.0992C2.92844 4.95123 2.87824 4.603 3.38456 4.16243C3.45238 4.10309 3.53035 4.05541 3.61204 4.01713C3.61429 5.0208 4.00699 5.90576 4.78879 6.63229C5.05685 6.8814 5.47574 6.86564 5.72439 6.59707C5.97304 6.32851 5.95731 5.90885 5.68924 5.65974C4.94982 4.97259 4.75497 4.13214 5.10062 3.01964C5.11014 2.989 5.11732 2.95818 5.12228 2.9274C5.22171 2.86194 5.33378 2.79857 5.46 2.73947C6.19219 2.39681 7.06406 2.56925 7.31612 2.63156C7.35649 2.64157 7.39905 2.62266 7.41978 2.58372C7.51472 2.40126 7.81589 1.8995 8.34621 1.70925C8.60181 1.61834 8.85713 1.60344 9.08786 1.62618C11.6068 4.06124 11.4366 5.68726 8.96062 7.43547C8.66175 7.6465 8.59023 8.06029 8.80086 8.35971C9.01149 8.65914 9.42452 8.7308 9.72339 8.51978C12.6397 6.46066 13.0392 4.11212 10.7442 1.44866C10.9443 1.3772 11.1884 1.32653 11.4823 1.32653C12.316 1.32653 12.819 1.75709 12.9412 1.89393C12.9674 1.92286 13.0078 1.93287 13.0416 1.9173C13.4267 1.75412 13.898 1.71226 14.2907 1.87609L14.434 1.94734C14.4408 1.95135 14.449 1.95593 14.4585 1.9612C14.5749 2.02594 14.8787 2.19484 15.0341 2.70721C15.0516 2.76395 15.1138 2.79065 15.1651 2.76618C16.4678 2.13703 18.3639 3.04236 18.6032 4.5174L18.622 4.67198L18.6612 5.11478C18.6645 5.15594 18.6907 5.1882 18.7278 5.20044C19.5826 5.46055 19.9782 6.56525 19.6669 7.32596C18.6908 7.37739 17.8646 7.60699 17.1982 8.00994C16.3977 7.68247 16.2175 7.20669 16.5179 6.3707C16.6418 6.02605 16.4633 5.64606 16.1193 5.52197C15.7753 5.39787 15.396 5.57667 15.2721 5.92133C14.7993 7.23683 15.124 8.2954 16.1501 8.95163C15.6522 9.60881 15.3437 10.4606 15.2365 11.5012C15.1989 11.8656 15.4633 12.1915 15.8271 12.2291C16.1908 12.2667 16.516 12.0018 16.5536 11.6374C16.6649 10.5562 17.0282 9.77736 17.6755 9.28506L17.685 9.27812L17.698 9.26816C18.2932 8.82611 19.124 8.62123 20.2148 8.64157C20.4244 9.04108 20.6154 9.55405 20.6614 10.2058C20.812 12.3186 19.7077 12.9605 19.4022 13.0962C19.3607 13.114 19.3389 13.1619 19.3509 13.2075L19.3777 13.3268C19.4312 13.612 19.4625 14.164 19.0977 14.7495C18.4987 15.713 17.3878 15.3937 17.0419 15.2646C17.0196 15.2559 16.997 15.2572 16.9775 15.2656C16.1055 14.9017 15.7214 14.3823 15.7214 13.6799C15.7214 13.3136 15.425 13.0166 15.0593 13.0166C14.6937 13.0166 14.3973 13.3136 14.3973 13.6799C14.3973 14.8471 14.9903 15.7312 16.0929 16.31C15.225 16.7316 13.9205 16.7496 13.3331 16.7577C13.1791 16.7598 13.0744 16.7613 13.0399 16.7691L13.0274 16.7755L12.6564 18.5978C12.6499 18.6312 12.6274 18.6571 12.5986 18.6679L12.568 18.6735H11.7998C11.7595 18.6735 11.7234 18.6457 11.7125 18.6045L11.5609 18.0591C11.3784 17.4227 11.0734 16.4247 10.7685 15.7231ZM13.4453 7.58702C13.1473 7.37481 12.734 7.44485 12.5222 7.74343C11.5667 9.09045 11.9054 10.4825 12.5222 11.5465C12.7168 11.8822 13.1391 11.9287 13.4417 11.723C13.7443 11.5174 13.8067 11.1516 13.6179 10.8018C13.1391 9.91461 13.007 9.34986 13.6015 8.51188C13.8133 8.21329 13.7434 7.79922 13.4453 7.58702Z" fill="#766DAA"/></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$KA',
                  '<svg viewBox="0 0 17 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill - rule="evenodd" clip - rule="evenodd" d = "M16.3611 4.5128C15.1533 1.31376 11.7754 -0.393279 8.22168 0.077096C6.98769 0.239777 5.81414 0.673717 4.81244 1.35194C2.97911 2.59507 1.71537 4.6096 1.45347 6.76454L1.42769 7.01414L1.42124 7.108C1.41167 7.29258 1.42215 7.46401 1.45474 7.7234L1.53449 8.31268C1.56758 8.59462 1.56685 8.74811 1.53402 8.88132C1.52306 8.92537 1.50005 8.98514 1.45119 9.07503L1.35678 9.23427C1.15356 9.55565 0.820151 9.96169 0.326746 10.4581C-0.289171 11.0791 0.00831968 12.144 0.861949 12.3418L1.33405 12.45L1.34142 13.2146C1.34717 13.7287 1.35307 14.0954 1.3601 14.3001L1.36755 14.4502C1.46443 15.6257 2.52614 16.1389 3.95556 15.9065L4.08525 15.8884C4.6671 15.8217 4.92587 16.0047 5.00968 16.3697L5.03802 16.6816L5.06029 16.9656C5.1 17.5459 5.57608 18 6.15601 18H12.783L12.8957 17.9943C13.4509 17.9374 13.8812 17.4643 13.8812 16.8934V15.0298L13.8836 14.7891C13.9057 13.6841 14.0846 12.8441 14.4685 12.4136C16.5826 10.0461 17.3757 7.20067 16.3611 4.5128ZM8.37588 1.24441C11.4184 0.8417 14.2583 2.27689 15.2595 4.92865C16.1032 7.16388 15.4342 9.56441 13.5899 11.6297L13.4764 11.7663C12.8955 12.5168 12.7038 13.6148 12.7038 15.0298L12.7032 16.8225H6.23059L6.20116 16.4734L6.16767 16.1651C5.92468 15.0933 5.03696 14.5368 3.76619 14.7444L3.61515 14.7662C2.88739 14.8576 2.56823 14.6835 2.54099 14.3531L2.53924 14.3249C2.5339 14.2187 2.52792 13.9187 2.5224 13.4986L2.50596 11.6495L2.21394 11.4808L2.17803 11.4622C2.07559 11.4141 1.89797 11.3664 1.58672 11.2958L1.2306 11.217L1.32958 11.117C2.19093 10.2244 2.56412 9.61796 2.67697 9.16429C2.75052 8.86583 2.75505 8.61422 2.70795 8.20682L2.61639 7.51982C2.59924 7.37069 2.59355 7.26884 2.59711 7.17597L2.60094 7.1136L2.62585 6.8782C2.85377 5.07743 3.92517 3.37619 5.47292 2.32671C6.31968 1.75339 7.31955 1.38367 8.37588 1.24441ZM5.14253 6.52317C5.15064 6.49451 5.1301 6.46694 5.10091 6.46478C5.01224 6.45991 4.84519 6.42315 4.69868 6.23339C4.54838 6.04038 4.43918 5.56679 4.71219 5.01481C4.91169 4.61475 5.23174 4.42607 5.34635 4.3693C5.36744 4.35849 5.37717 4.33362 5.36798 4.31145C5.33986 4.23955 5.31499 4.07033 5.56585 3.85624C5.70695 3.73514 5.93672 3.71406 6.01943 3.71081C6.03836 3.71027 6.05404 3.69892 6.06052 3.68108C6.0908 3.59566 6.21028 3.34102 6.59412 3.16478C6.95689 2.99826 7.38885 3.08206 7.51373 3.11234C7.53374 3.1172 7.55482 3.10801 7.56509 3.08909C7.61213 3.00043 7.76134 2.7566 8.02409 2.66415C8.37279 2.54251 8.72042 2.70092 8.81557 2.75011C8.83179 2.75822 8.85017 2.75606 8.86369 2.74579C8.8699 2.74091 8.87706 2.73502 8.88519 2.72833C8.97612 2.65354 9.18931 2.47818 9.57786 2.47818C9.9909 2.47818 10.2401 2.6874 10.3007 2.7539C10.3137 2.76796 10.3337 2.77282 10.3504 2.76525C10.565 2.67605 10.8337 2.66145 11.0403 2.77985C11.0436 2.7818 11.0477 2.78403 11.0524 2.78659C11.1101 2.81805 11.2606 2.90012 11.3376 3.1491C11.3463 3.17667 11.3771 3.18965 11.4025 3.17775C12.0702 2.86148 13.0525 3.34318 13.1152 4.10385L13.1347 4.31902C13.1363 4.33902 13.1493 4.3547 13.1676 4.36065C13.6223 4.49635 13.8148 5.1051 13.5931 5.47218C13.5654 5.51781 13.6192 5.59474 13.7022 5.71326C13.8492 5.92335 14.0876 6.26412 14.1256 6.79294C14.2002 7.81959 13.6531 8.13154 13.5017 8.19749C13.4812 8.20615 13.4704 8.22939 13.4763 8.25156C13.5055 8.35914 13.5618 8.66892 13.3509 9.00087C13.0541 9.46905 12.5037 9.31389 12.3324 9.25118C12.3053 9.24091 12.2778 9.25929 12.2724 9.2874C12.1593 9.95419 10.9299 9.97084 10.4949 9.97673C10.4015 9.978 10.3447 9.97877 10.3434 9.98536L10.1596 10.8709C10.1552 10.8925 10.1369 10.9077 10.1158 10.9077H9.73518C9.71518 10.9077 9.69734 10.8942 9.69193 10.8741C9.6303 10.6487 9.26808 9.3512 9.01074 9.11548C8.77705 8.90144 8.4865 8.83523 8.19111 8.76792C8.17761 8.76484 8.16411 8.76176 8.15059 8.75867C7.8473 8.68947 7.54401 8.58404 7.31965 8.3559C7.27891 8.31434 7.23514 8.26717 7.18796 8.21634C6.89697 7.90284 6.47634 7.44966 5.83995 7.3087C5.05063 7.13462 5.09712 6.6859 5.14253 6.52317Z" fill = "#766DAA" /></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$PRACTICE',
                  '<svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" class="strock">                            <path _ngcontent-atw-c150="" fill-rule="evenodd" clip-rule="evenodd"                              d="M11.6405 0C11.7729 0 11.9014 0.0389825 12.01 0.110787L12.0874 0.170698L15.3826 3.13757C15.4918 3.23587 15.5634 3.36654 15.5877 3.50795L15.5968 3.61568V7.65373C15.5968 8.01206 15.3009 8.30254 14.9358 8.30254C14.6039 8.30254 14.3291 8.06247 14.2819 7.7496L14.2747 7.65373L14.2738 3.89984L11.3834 1.29762H1.67807C1.50606 1.29762 1.36254 1.41737 1.32935 1.57657L1.32212 1.64698V16.4629C1.32212 16.6317 1.44413 16.7726 1.60633 16.8052L1.67807 16.8123H7.2886C7.6537 16.8123 7.94966 17.1027 7.94966 17.4611C7.94966 17.7868 7.70506 18.0565 7.38629 18.1028L7.2886 18.1099H1.67807C0.800076 18.1099 0.0795701 17.4481 0.00615952 16.605L0 16.4629V1.64698C0 0.785251 0.674295 0.0780957 1.53328 0.00604539L1.67807 0H11.6405ZM7.29885 4.83557C7.03452 4.5884 6.61609 4.59834 6.36425 4.85777L4.83691 6.4302L4.18769 5.84445L4.10287 5.77951C3.83689 5.60799 3.47593 5.64585 3.25365 5.88335C3.00667 6.14725 3.02442 6.55768 3.29329 6.80008L4.42129 7.81704L4.50499 7.88125C4.76743 8.0512 5.12336 8.01725 5.3471 7.78676L7.32147 5.75286L7.38917 5.67081C7.56874 5.41293 7.53675 5.05803 7.29885 4.83557ZM15.999 10.0658L11.176 15.5103C11.1022 15.5936 11.0512 15.694 11.0278 15.8019L10.5033 18.2217C10.3953 18.7198 10.8867 19.1391 11.3744 18.9648L13.7433 18.1183C13.849 18.0805 13.9431 18.017 14.0169 17.9337L18.8399 12.4891C19.0798 12.2184 19.0511 11.8086 18.7759 11.5738L16.9316 10.0006C16.6564 9.76583 16.2388 9.79502 15.999 10.0658ZM16.5607 11.4058L17.4085 12.129L13.1318 16.9558L12.0437 17.3451L12.2849 16.2316L16.5607 11.4058ZM7.29885 8.99618C7.03452 8.74901 6.61609 8.75895 6.36425 9.01838L4.83691 10.5906L4.18769 10.0051L4.10287 9.94012C3.83689 9.7686 3.47593 9.80646 3.25365 10.044C3.00667 10.3079 3.02442 10.7183 3.29329 10.9607L4.42129 11.9776L4.50499 12.0419C4.76743 12.2118 5.12336 12.1779 5.3471 11.9474L7.32147 9.91347L7.38917 9.83142C7.56874 9.57353 7.53675 9.21864 7.29885 8.99618ZM11.3275 10.2317C11.6926 10.2317 11.9885 10.5222 11.9885 10.8805C11.9885 11.2063 11.7439 11.4759 11.4252 11.5223L11.3275 11.5293H9.3688C9.0037 11.5293 8.70774 11.2388 8.70774 10.8805C8.70774 10.5548 8.95234 10.2851 9.27111 10.2387L9.3688 10.2317H11.3275ZM11.9885 6.7199C11.9885 6.36157 11.6926 6.07109 11.3275 6.07109H9.3688L9.27111 6.07813C8.95234 6.12447 8.70774 6.39415 8.70774 6.7199C8.70774 7.07823 9.0037 7.36871 9.3688 7.36871H11.3275L11.4252 7.36167C11.7439 7.31533 11.9885 7.04565 11.9885 6.7199Z"                              fill="#766DAA"></path>                          </svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$VideoLesson',
                  '<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M0 15.6425V2.35735C0 0.630217 1.70499 -0.572385 3.2016 0.281519L14.8438 6.92371C16.3854 7.8033 16.3854 10.1966 14.8438 11.0762L3.2016 17.7184C1.70486 18.5724 0 17.3703 0 15.6425ZM14.1033 8.09732L2.4611 1.45513C2.01709 1.20179 1.43926 1.60936 1.43926 2.35735V15.6425C1.43926 16.391 2.01682 16.7983 2.46112 16.5448L14.1033 9.90258C14.7132 9.55458 14.7132 8.44532 14.1033 8.09732Z" fill="#766DAA"/><defs><linearGradient id="paint0_linear" x1="-2.39148" y1="-7.39981" x2="-2.39148" y2="18" gradientUnits="userSpaceOnUse"><stop stop-color="#E56F9F"/><stop offset="1" stop-color="#EA635F"/></linearGradient></defs></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$Events',
                  '<svg viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.47482 0C3.41912 0 1.75264 1.63033 1.75264 3.64146C1.75264 5.65258 3.41912 7.28292 5.47482 7.28292C7.53052 7.28292 9.197 5.65258 9.197 3.64146C9.197 1.63033 7.53052 0 5.47482 0ZM5.47482 1.28169C6.80698 1.28169 7.8869 2.33819 7.8869 3.64146C7.8869 4.94472 6.80698 6.00122 5.47482 6.00122C4.14266 6.00122 3.06274 4.94472 3.06274 3.64146C3.06274 2.33819 4.14266 1.28169 5.47482 1.28169ZM10.9496 9.13341C10.9496 8.77948 10.6564 8.49256 10.2946 8.49256H0.655051C0.293276 8.49256 0 8.77948 0 9.13341L0.00490631 9.44283C0.0865017 11.9957 1.18142 13.9085 2.95869 15.0774L3.06664 15.1456L3.06713 20.3592C3.06713 20.7131 3.3604 21 3.72218 21H7.22746L7.32426 20.9931C7.64014 20.9473 7.88251 20.6809 7.88251 20.3592L7.88177 15.1456L7.99101 15.0772C9.8391 13.8613 10.9496 11.8411 10.9496 9.13341ZM9.61312 9.77338L9.59562 9.98296C9.38238 11.9801 8.40387 13.3938 6.90333 14.2297L6.82058 14.2843C6.66523 14.4048 6.57241 14.5892 6.57241 14.7866L6.57167 19.7183H4.37675L4.37723 14.7866C4.37723 14.5562 4.25084 14.3436 4.04618 14.2296L3.84481 14.1121C2.45815 13.2644 1.55751 11.8897 1.35401 9.98311L1.3353 9.77338H9.61312ZM20.3449 0.857318C20.6738 0.857318 20.9461 1.09444 20.9929 1.40346L21 1.49816V12.6433C21 12.965 20.7576 13.2314 20.4417 13.2772L20.3449 13.2841H12.0199C11.6581 13.2841 11.3648 12.9972 11.3648 12.6433C11.3648 12.3215 11.6072 12.0552 11.9231 12.0094L12.0199 12.0024L19.6898 12.0015V2.13845L11.1436 2.13901C10.8147 2.13901 10.5424 1.90189 10.4956 1.59286L10.4885 1.49816C10.4885 1.17641 10.7309 0.910038 11.0468 0.864266L11.1436 0.857318H20.3449ZM18.8928 4.33589C18.8928 3.98196 18.5995 3.69504 18.2378 3.69504H12.6163L12.5195 3.70199C12.2037 3.74776 11.9613 4.01413 11.9613 4.33589C11.9613 4.68981 12.2546 4.97673 12.6163 4.97673H18.2378L18.3346 4.96978C18.6504 4.92401 18.8928 4.65764 18.8928 4.33589ZM18.2378 6.26699C18.5995 6.26699 18.8928 6.55391 18.8928 6.90784C18.8928 7.22959 18.6504 7.49596 18.3346 7.54173L18.2378 7.54868H14.369C14.0072 7.54868 13.7139 7.26177 13.7139 6.90784C13.7139 6.58608 13.9563 6.31971 14.2722 6.27394L14.369 6.26699H18.2378ZM18.8928 9.47979C18.8928 9.12586 18.5995 8.83895 18.2378 8.83895H16.1216L16.0248 8.84589C15.7089 8.89167 15.4666 9.15804 15.4666 9.47979C15.4666 9.83372 15.7598 10.1206 16.1216 10.1206H18.2378L18.3346 10.1137C18.6504 10.0679 18.8928 9.80155 18.8928 9.47979Z" /></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$CAT',
                  '<svg _ngcontent-drh-c240="" _ngcontent-ygw-c83="" viewBox="0 0 25 25 " fill="none " xmlns="http://www.w3.org/2000/svg " class="strock st-fill"><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" fill-rule="evenodd " clip-rule="evenodd " d="M17.159 22.5804L14.1838 23.6601L14.8389 20.5636L20.8901 13.6026L23.2101 15.6193L17.159 22.5804Z " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M8.76697 6.96094L6.28636 9.56458L4.86914 8.26276 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M9.32686 22.5217H2C1.44771 22.5217 1 22.074 1 21.5217V2C1 1.44772 1.44772 1 2 1L14.7946 1L18.9348 4.79795V9.96715 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M8.76697 12.2871L6.28636 14.8908L4.86914 13.5889 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M11.9404 14.0978H14.4013 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M11.9404 8.77165H14.4013 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path></svg>'
                );
                let eventElement = info.el;
                let start = new Date(info.event.start);
                let end = new Date(info.event.end);
                let diffInMilliseconds = Math.abs(
                  end.getTime() - start.getTime()
                );
                let hours = Math.floor(diffInMilliseconds / (1000 * 60 * 60));
                let minute =
                  Math.floor(diffInMilliseconds % (1000 * 60 * 60)) /
                  (1000 * 60);
                let durationText =
                  hours == 0
                    ? 'Duration(' + minute + 'M)'
                    : minute == 0
                      ? 'Duration(' + hours + 'H)'
                      : 'Duration(' + hours + 'H' + ' ' + minute + 'M)';

                let durationElement = document.createElement('div');
                durationElement.classList.add('fc-duration');
                durationElement.innerText = durationText;
                let fcTime = eventElement.querySelector('.fc-time');
                fcTime.after(durationElement);
              },
            }).render();
          } else {
            if (HomeeventData.length > 0) {
              let defaultDate =
                HomeeventData.length > 1
                  ? new Date(HomeeventData[1].start)
                  : new Date(HomeeventData[0].start);
              let calendarElHome: HTMLElement = document.getElementById(
                'calendar' + (i + 1)
              );
              calendarElHome.setAttribute('class', 'homecalendar');
              let me = this;
              new Calendar(calendarElHome, {
                plugins: [],
                defaultView: window.innerWidth > 768 ? 'agendaWeek' : 'agendaDay',
                defaultDate: defaultDate,
                showNonCurrentDates: true,
                editable: false,
                eventLimit: 2,
                events: [],
                allDaySlot: false,
                eventOverlap: false,
                timeZone: 'local',
                columnHeaderFormat: {
                  weekday: 'short',
                  month: 'short',
                  day: 'numeric',
                },
                displayEventTime: true,
                eventTimeFormat: {
                  hour: 'numeric',
                  minute: '2-digit',
                  meridiem: 'short',
                },
                buttonText: {
                  today: 'Today',
                },
                header: false,
                minTime: { hours: 0 },
                maxTime: { hours: 0, seconds: 1 },
                slotDuration: {
                  minute: 1,
                },
                columnHeaderHtml: function (params) {
                  var fulldate = new Date(params.toString());
                  let dt = fulldate.getUTCDate();
                  let mon = me.months[fulldate.getUTCMonth()];
                  let current_date = me.auth.ConvertDateDDFormat(
                    new Date(),
                    me.timezone,
                    'DD'
                  );
                  let current_month = me.auth.ConvertDateDDFormat(
                    new Date(),
                    me.timezone,
                    'MM'
                  );
                  let cls = '';
                  if (
                    parseInt(current_date) == dt &&
                    mon == me.months[parseInt(current_month) - 1]
                  ) {
                    cls = 'active';
                  }
                  let day = days[fulldate.getUTCDay()];
                  let year = fulldate.getUTCFullYear().toString().substr(2, 3);
                  let res = `<div class="date-head"><span class="main-date ${cls}">${dt}</span>
                  <div class="date-month">
                    <span class="${cls}">${day}</span>
                    <span  class="${cls}">${mon}'${year}</span>
                  </div></div>`;
                  return res;
                },
              }).render();
            }
          }

          if (HomeeventData.length > 0) {
            let dateArray = [];
            let dateEndArray = [];
            let changeDate = false;
            HomeeventData.forEach((element) => {
              if (
                new Date(element.start).toDateString() <
                new Date(element.end).toDateString()
              ) {
                changeDate = true;
              }
              dateArray.push(new Date(element.start).getHours());
              dateArray.push(new Date(element.end).getHours());
              dateEndArray.push(new Date(element.start).getHours());
              dateEndArray.push(new Date(element.end).getHours());
            });
            var hour = dateArray.reduce(function (a, b) {
              return a < b ? a : b;
            });
            var endhour = dateEndArray.reduce(function (a, b) {
              return a > b ? a : b;
            });
            if (changeDate) {
              hour = 0;
              endhour = 24;
              changeDate = false;
            }
            let defaultDate = new Date(HomeeventData[0].start);
            let me = this;
            let calendarElHome: HTMLElement = document.getElementById(
              'homecalendar' + (i + 1)
            );
            new Calendar(calendarElHome, {
              plugins: [],
              defaultView: window.innerWidth > 768 ? 'agendaWeek' : 'agendaDay',
              defaultDate: defaultDate,
              editable: false,
              eventLimit: 2,
              events: HomeeventData,
              allDaySlot: false,
              eventOverlap: false,
              columnHeaderFormat: {
                weekday: 'short',
                month: 'short',
                day: 'numeric',
              },
              displayEventTime: true,
              eventTimeFormat: {
                hour: 'numeric',
                minute: '2-digit',
                meridiem: 'short',
              },
              buttonText: {
                today: 'Today',
              },
              header: false,
              columnHeader: false,

              slotDuration: {
                minutes: 30,
              },
              minTime: { hours: hour },
              maxTime: { hours: endhour + 1 },
              eventClick: function (info) {
                me.eventInnerHtml = me.sanitizer.bypassSecurityTrustHtml(
                  info.el.innerHTML
                );
                me.iSMoreEventPopup = true;
                me.EventLeft = info.jsEvent.clientX;
                me.EventTop = info.jsEvent.clientY;
                me.SelectedEvent = info.event.extendedProps.event_data;
              },
              eventRender: function (info) {
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$MindMap',
                  '<svg width="22" height="20" viewBox="0 0 22 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M9.89476 0.375206C10.2885 0.170633 10.7323 0.0410951 11.2294 0.00825915L11.4823 0C12.1668 0 12.7743 0.184647 13.2528 0.464229L13.28 0.480941L13.3201 0.474429C13.8633 0.397683 14.4215 0.466498 14.9211 0.706172L15.1056 0.804108C15.3682 0.958994 15.4758 1.02641 15.6146 1.16777L15.6969 1.25645L15.7645 1.24925C17.6013 1.0833 19.5332 2.3416 19.8923 4.19938L19.9146 4.3391L20.0302 4.42896C20.8658 5.12651 21.2613 6.30579 21.0349 7.36596L21.0217 7.41564L21.0402 7.44401C21.2014 7.55084 21.3121 7.72594 21.3336 7.92536C21.6958 8.58395 21.9243 9.29109 21.9821 10.1113C22.1036 11.8158 21.5959 13.0272 20.7795 13.7618L20.7376 13.7973L20.7248 14.0144C20.6843 14.4155 20.5643 14.83 20.3416 15.244L20.2216 15.4509C19.7134 16.2682 18.93 16.6867 18.0564 16.7408C17.9796 16.7455 17.9036 16.7475 17.8285 16.747L17.7411 16.7428C17.7242 16.75 17.707 16.7565 17.6895 16.7623L17.66 16.7991C17.1563 17.3789 16.3703 17.721 15.4089 17.9074L15.2002 17.945C14.8528 18.0031 14.4937 18.0395 14.1159 18.0606L13.9556 18.8536C13.8352 19.4676 13.3272 19.9341 12.7034 19.9936L12.568 20H11.7998C11.1538 20 10.5965 19.5625 10.4338 18.9486C10.2237 18.1652 9.91752 17.195 9.69557 16.5744C9.60245 16.4821 9.53567 16.3613 9.51034 16.2225C9.49788 16.1541 9.48617 16.0866 9.47522 16.0197C9.45854 15.9869 9.44491 15.9651 9.43481 15.9557C9.26814 15.8001 9.05269 15.7177 8.39742 15.5654L8.04114 15.4783C7.19044 15.2517 6.52719 14.9194 5.97064 14.3424C6.00795 14.3812 5.33067 13.6438 5.11846 13.4403L4.93371 13.2707C4.50545 12.8953 4.09448 12.6624 3.64782 12.5615C2.18597 12.2328 1.39635 11.4198 1.20379 10.4731L1.20031 10.4524L1.11956 10.3972C0.974895 10.2897 0.836952 10.1626 0.708256 10.015L0.582735 9.86044C-0.129563 8.92782 -0.215357 7.38097 0.47255 5.96296C0.781601 5.33105 1.19484 4.8439 1.64185 4.48544L1.67901 4.45645L1.70986 4.34066C1.82042 3.97769 2.03854 3.62199 2.36634 3.29946L2.51354 3.16333C2.80049 2.91224 3.11313 2.75465 3.44268 2.65986L3.51438 2.64115L3.56002 2.57977C3.83008 2.22805 4.20156 1.90535 4.68536 1.64518L4.89961 1.53761C5.51069 1.25162 6.14012 1.16636 6.7467 1.2043L6.77467 1.20645L6.89742 1.08084C7.12338 0.863657 7.39032 0.67749 7.70711 0.537493L7.90323 0.459157C8.5354 0.234315 9.13565 0.235922 9.68341 0.371026L9.82921 0.411554L9.89476 0.375206ZM10.7685 15.7231C10.5432 14.2905 10.749 13.5679 11.2347 13.3834L11.3236 13.342C11.6054 13.1843 11.7369 12.8395 11.619 12.5281C11.4894 12.1856 11.1072 12.0132 10.7653 12.1431C9.87017 12.4831 9.42343 13.2739 9.36515 14.4477C9.25035 14.4111 9.13353 14.3792 9.01553 14.3494L8.60154 14.2511C7.98939 14.1087 7.37723 13.8917 6.92438 13.4222C6.84217 13.3367 6.75382 13.2396 6.65858 13.135C6.55807 13.0246 6.44989 12.9058 6.33318 12.7832C7.34978 12.587 8.08811 11.8348 8.47052 10.5268C8.5733 10.1752 8.37216 9.80676 8.02127 9.70379C7.67038 9.60083 7.30261 9.80233 7.19983 10.1539C6.76429 11.6436 5.83176 11.9172 3.94099 10.9754C3.7108 10.8608 3.44603 10.8928 3.25252 11.0359C2.37712 10.6065 2.45439 9.92748 2.53015 9.65066C2.54652 9.59169 2.50506 9.53495 2.44613 9.5305C2.26718 9.52049 1.93 9.44484 1.63429 9.05433C1.33094 8.65715 1.11051 7.68255 1.66157 6.54663C2.06422 5.72334 2.7102 5.33506 2.94153 5.21824C2.98409 5.19599 3.00373 5.14482 2.98518 5.0992C2.92844 4.95123 2.87824 4.603 3.38456 4.16243C3.45238 4.10309 3.53035 4.05541 3.61204 4.01713C3.61429 5.0208 4.00699 5.90576 4.78879 6.63229C5.05685 6.8814 5.47574 6.86564 5.72439 6.59707C5.97304 6.32851 5.95731 5.90885 5.68924 5.65974C4.94982 4.97259 4.75497 4.13214 5.10062 3.01964C5.11014 2.989 5.11732 2.95818 5.12228 2.9274C5.22171 2.86194 5.33378 2.79857 5.46 2.73947C6.19219 2.39681 7.06406 2.56925 7.31612 2.63156C7.35649 2.64157 7.39905 2.62266 7.41978 2.58372C7.51472 2.40126 7.81589 1.8995 8.34621 1.70925C8.60181 1.61834 8.85713 1.60344 9.08786 1.62618C11.6068 4.06124 11.4366 5.68726 8.96062 7.43547C8.66175 7.6465 8.59023 8.06029 8.80086 8.35971C9.01149 8.65914 9.42452 8.7308 9.72339 8.51978C12.6397 6.46066 13.0392 4.11212 10.7442 1.44866C10.9443 1.3772 11.1884 1.32653 11.4823 1.32653C12.316 1.32653 12.819 1.75709 12.9412 1.89393C12.9674 1.92286 13.0078 1.93287 13.0416 1.9173C13.4267 1.75412 13.898 1.71226 14.2907 1.87609L14.434 1.94734C14.4408 1.95135 14.449 1.95593 14.4585 1.9612C14.5749 2.02594 14.8787 2.19484 15.0341 2.70721C15.0516 2.76395 15.1138 2.79065 15.1651 2.76618C16.4678 2.13703 18.3639 3.04236 18.6032 4.5174L18.622 4.67198L18.6612 5.11478C18.6645 5.15594 18.6907 5.1882 18.7278 5.20044C19.5826 5.46055 19.9782 6.56525 19.6669 7.32596C18.6908 7.37739 17.8646 7.60699 17.1982 8.00994C16.3977 7.68247 16.2175 7.20669 16.5179 6.3707C16.6418 6.02605 16.4633 5.64606 16.1193 5.52197C15.7753 5.39787 15.396 5.57667 15.2721 5.92133C14.7993 7.23683 15.124 8.2954 16.1501 8.95163C15.6522 9.60881 15.3437 10.4606 15.2365 11.5012C15.1989 11.8656 15.4633 12.1915 15.8271 12.2291C16.1908 12.2667 16.516 12.0018 16.5536 11.6374C16.6649 10.5562 17.0282 9.77736 17.6755 9.28506L17.685 9.27812L17.698 9.26816C18.2932 8.82611 19.124 8.62123 20.2148 8.64157C20.4244 9.04108 20.6154 9.55405 20.6614 10.2058C20.812 12.3186 19.7077 12.9605 19.4022 13.0962C19.3607 13.114 19.3389 13.1619 19.3509 13.2075L19.3777 13.3268C19.4312 13.612 19.4625 14.164 19.0977 14.7495C18.4987 15.713 17.3878 15.3937 17.0419 15.2646C17.0196 15.2559 16.997 15.2572 16.9775 15.2656C16.1055 14.9017 15.7214 14.3823 15.7214 13.6799C15.7214 13.3136 15.425 13.0166 15.0593 13.0166C14.6937 13.0166 14.3973 13.3136 14.3973 13.6799C14.3973 14.8471 14.9903 15.7312 16.0929 16.31C15.225 16.7316 13.9205 16.7496 13.3331 16.7577C13.1791 16.7598 13.0744 16.7613 13.0399 16.7691L13.0274 16.7755L12.6564 18.5978C12.6499 18.6312 12.6274 18.6571 12.5986 18.6679L12.568 18.6735H11.7998C11.7595 18.6735 11.7234 18.6457 11.7125 18.6045L11.5609 18.0591C11.3784 17.4227 11.0734 16.4247 10.7685 15.7231ZM13.4453 7.58702C13.1473 7.37481 12.734 7.44485 12.5222 7.74343C11.5667 9.09045 11.9054 10.4825 12.5222 11.5465C12.7168 11.8822 13.1391 11.9287 13.4417 11.723C13.7443 11.5174 13.8067 11.1516 13.6179 10.8018C13.1391 9.91461 13.007 9.34986 13.6015 8.51188C13.8133 8.21329 13.7434 7.79922 13.4453 7.58702Z" fill="#766DAA"/></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$KA',
                  '<svg viewBox="0 0 17 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill - rule="evenodd" clip - rule="evenodd" d = "M16.3611 4.5128C15.1533 1.31376 11.7754 -0.393279 8.22168 0.077096C6.98769 0.239777 5.81414 0.673717 4.81244 1.35194C2.97911 2.59507 1.71537 4.6096 1.45347 6.76454L1.42769 7.01414L1.42124 7.108C1.41167 7.29258 1.42215 7.46401 1.45474 7.7234L1.53449 8.31268C1.56758 8.59462 1.56685 8.74811 1.53402 8.88132C1.52306 8.92537 1.50005 8.98514 1.45119 9.07503L1.35678 9.23427C1.15356 9.55565 0.820151 9.96169 0.326746 10.4581C-0.289171 11.0791 0.00831968 12.144 0.861949 12.3418L1.33405 12.45L1.34142 13.2146C1.34717 13.7287 1.35307 14.0954 1.3601 14.3001L1.36755 14.4502C1.46443 15.6257 2.52614 16.1389 3.95556 15.9065L4.08525 15.8884C4.6671 15.8217 4.92587 16.0047 5.00968 16.3697L5.03802 16.6816L5.06029 16.9656C5.1 17.5459 5.57608 18 6.15601 18H12.783L12.8957 17.9943C13.4509 17.9374 13.8812 17.4643 13.8812 16.8934V15.0298L13.8836 14.7891C13.9057 13.6841 14.0846 12.8441 14.4685 12.4136C16.5826 10.0461 17.3757 7.20067 16.3611 4.5128ZM8.37588 1.24441C11.4184 0.8417 14.2583 2.27689 15.2595 4.92865C16.1032 7.16388 15.4342 9.56441 13.5899 11.6297L13.4764 11.7663C12.8955 12.5168 12.7038 13.6148 12.7038 15.0298L12.7032 16.8225H6.23059L6.20116 16.4734L6.16767 16.1651C5.92468 15.0933 5.03696 14.5368 3.76619 14.7444L3.61515 14.7662C2.88739 14.8576 2.56823 14.6835 2.54099 14.3531L2.53924 14.3249C2.5339 14.2187 2.52792 13.9187 2.5224 13.4986L2.50596 11.6495L2.21394 11.4808L2.17803 11.4622C2.07559 11.4141 1.89797 11.3664 1.58672 11.2958L1.2306 11.217L1.32958 11.117C2.19093 10.2244 2.56412 9.61796 2.67697 9.16429C2.75052 8.86583 2.75505 8.61422 2.70795 8.20682L2.61639 7.51982C2.59924 7.37069 2.59355 7.26884 2.59711 7.17597L2.60094 7.1136L2.62585 6.8782C2.85377 5.07743 3.92517 3.37619 5.47292 2.32671C6.31968 1.75339 7.31955 1.38367 8.37588 1.24441ZM5.14253 6.52317C5.15064 6.49451 5.1301 6.46694 5.10091 6.46478C5.01224 6.45991 4.84519 6.42315 4.69868 6.23339C4.54838 6.04038 4.43918 5.56679 4.71219 5.01481C4.91169 4.61475 5.23174 4.42607 5.34635 4.3693C5.36744 4.35849 5.37717 4.33362 5.36798 4.31145C5.33986 4.23955 5.31499 4.07033 5.56585 3.85624C5.70695 3.73514 5.93672 3.71406 6.01943 3.71081C6.03836 3.71027 6.05404 3.69892 6.06052 3.68108C6.0908 3.59566 6.21028 3.34102 6.59412 3.16478C6.95689 2.99826 7.38885 3.08206 7.51373 3.11234C7.53374 3.1172 7.55482 3.10801 7.56509 3.08909C7.61213 3.00043 7.76134 2.7566 8.02409 2.66415C8.37279 2.54251 8.72042 2.70092 8.81557 2.75011C8.83179 2.75822 8.85017 2.75606 8.86369 2.74579C8.8699 2.74091 8.87706 2.73502 8.88519 2.72833C8.97612 2.65354 9.18931 2.47818 9.57786 2.47818C9.9909 2.47818 10.2401 2.6874 10.3007 2.7539C10.3137 2.76796 10.3337 2.77282 10.3504 2.76525C10.565 2.67605 10.8337 2.66145 11.0403 2.77985C11.0436 2.7818 11.0477 2.78403 11.0524 2.78659C11.1101 2.81805 11.2606 2.90012 11.3376 3.1491C11.3463 3.17667 11.3771 3.18965 11.4025 3.17775C12.0702 2.86148 13.0525 3.34318 13.1152 4.10385L13.1347 4.31902C13.1363 4.33902 13.1493 4.3547 13.1676 4.36065C13.6223 4.49635 13.8148 5.1051 13.5931 5.47218C13.5654 5.51781 13.6192 5.59474 13.7022 5.71326C13.8492 5.92335 14.0876 6.26412 14.1256 6.79294C14.2002 7.81959 13.6531 8.13154 13.5017 8.19749C13.4812 8.20615 13.4704 8.22939 13.4763 8.25156C13.5055 8.35914 13.5618 8.66892 13.3509 9.00087C13.0541 9.46905 12.5037 9.31389 12.3324 9.25118C12.3053 9.24091 12.2778 9.25929 12.2724 9.2874C12.1593 9.95419 10.9299 9.97084 10.4949 9.97673C10.4015 9.978 10.3447 9.97877 10.3434 9.98536L10.1596 10.8709C10.1552 10.8925 10.1369 10.9077 10.1158 10.9077H9.73518C9.71518 10.9077 9.69734 10.8942 9.69193 10.8741C9.6303 10.6487 9.26808 9.3512 9.01074 9.11548C8.77705 8.90144 8.4865 8.83523 8.19111 8.76792C8.17761 8.76484 8.16411 8.76176 8.15059 8.75867C7.8473 8.68947 7.54401 8.58404 7.31965 8.3559C7.27891 8.31434 7.23514 8.26717 7.18796 8.21634C6.89697 7.90284 6.47634 7.44966 5.83995 7.3087C5.05063 7.13462 5.09712 6.6859 5.14253 6.52317Z" fill = "#766DAA" /></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$PRACTICE',
                  '<svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" class="strock">                            <path _ngcontent-atw-c150="" fill-rule="evenodd" clip-rule="evenodd"                              d="M11.6405 0C11.7729 0 11.9014 0.0389825 12.01 0.110787L12.0874 0.170698L15.3826 3.13757C15.4918 3.23587 15.5634 3.36654 15.5877 3.50795L15.5968 3.61568V7.65373C15.5968 8.01206 15.3009 8.30254 14.9358 8.30254C14.6039 8.30254 14.3291 8.06247 14.2819 7.7496L14.2747 7.65373L14.2738 3.89984L11.3834 1.29762H1.67807C1.50606 1.29762 1.36254 1.41737 1.32935 1.57657L1.32212 1.64698V16.4629C1.32212 16.6317 1.44413 16.7726 1.60633 16.8052L1.67807 16.8123H7.2886C7.6537 16.8123 7.94966 17.1027 7.94966 17.4611C7.94966 17.7868 7.70506 18.0565 7.38629 18.1028L7.2886 18.1099H1.67807C0.800076 18.1099 0.0795701 17.4481 0.00615952 16.605L0 16.4629V1.64698C0 0.785251 0.674295 0.0780957 1.53328 0.00604539L1.67807 0H11.6405ZM7.29885 4.83557C7.03452 4.5884 6.61609 4.59834 6.36425 4.85777L4.83691 6.4302L4.18769 5.84445L4.10287 5.77951C3.83689 5.60799 3.47593 5.64585 3.25365 5.88335C3.00667 6.14725 3.02442 6.55768 3.29329 6.80008L4.42129 7.81704L4.50499 7.88125C4.76743 8.0512 5.12336 8.01725 5.3471 7.78676L7.32147 5.75286L7.38917 5.67081C7.56874 5.41293 7.53675 5.05803 7.29885 4.83557ZM15.999 10.0658L11.176 15.5103C11.1022 15.5936 11.0512 15.694 11.0278 15.8019L10.5033 18.2217C10.3953 18.7198 10.8867 19.1391 11.3744 18.9648L13.7433 18.1183C13.849 18.0805 13.9431 18.017 14.0169 17.9337L18.8399 12.4891C19.0798 12.2184 19.0511 11.8086 18.7759 11.5738L16.9316 10.0006C16.6564 9.76583 16.2388 9.79502 15.999 10.0658ZM16.5607 11.4058L17.4085 12.129L13.1318 16.9558L12.0437 17.3451L12.2849 16.2316L16.5607 11.4058ZM7.29885 8.99618C7.03452 8.74901 6.61609 8.75895 6.36425 9.01838L4.83691 10.5906L4.18769 10.0051L4.10287 9.94012C3.83689 9.7686 3.47593 9.80646 3.25365 10.044C3.00667 10.3079 3.02442 10.7183 3.29329 10.9607L4.42129 11.9776L4.50499 12.0419C4.76743 12.2118 5.12336 12.1779 5.3471 11.9474L7.32147 9.91347L7.38917 9.83142C7.56874 9.57353 7.53675 9.21864 7.29885 8.99618ZM11.3275 10.2317C11.6926 10.2317 11.9885 10.5222 11.9885 10.8805C11.9885 11.2063 11.7439 11.4759 11.4252 11.5223L11.3275 11.5293H9.3688C9.0037 11.5293 8.70774 11.2388 8.70774 10.8805C8.70774 10.5548 8.95234 10.2851 9.27111 10.2387L9.3688 10.2317H11.3275ZM11.9885 6.7199C11.9885 6.36157 11.6926 6.07109 11.3275 6.07109H9.3688L9.27111 6.07813C8.95234 6.12447 8.70774 6.39415 8.70774 6.7199C8.70774 7.07823 9.0037 7.36871 9.3688 7.36871H11.3275L11.4252 7.36167C11.7439 7.31533 11.9885 7.04565 11.9885 6.7199Z"                              fill="#766DAA"></path>                          </svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$VideoLesson',
                  '<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M0 15.6425V2.35735C0 0.630217 1.70499 -0.572385 3.2016 0.281519L14.8438 6.92371C16.3854 7.8033 16.3854 10.1966 14.8438 11.0762L3.2016 17.7184C1.70486 18.5724 0 17.3703 0 15.6425ZM14.1033 8.09732L2.4611 1.45513C2.01709 1.20179 1.43926 1.60936 1.43926 2.35735V15.6425C1.43926 16.391 2.01682 16.7983 2.46112 16.5448L14.1033 9.90258C14.7132 9.55458 14.7132 8.44532 14.1033 8.09732Z" fill="#766DAA"/><defs><linearGradient id="paint0_linear" x1="-2.39148" y1="-7.39981" x2="-2.39148" y2="18" gradientUnits="userSpaceOnUse"><stop stop-color="#E56F9F"/><stop offset="1" stop-color="#EA635F"/></linearGradient></defs></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$Events',
                  '<svg  viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.47482 0C3.41912 0 1.75264 1.63033 1.75264 3.64146C1.75264 5.65258 3.41912 7.28292 5.47482 7.28292C7.53052 7.28292 9.197 5.65258 9.197 3.64146C9.197 1.63033 7.53052 0 5.47482 0ZM5.47482 1.28169C6.80698 1.28169 7.8869 2.33819 7.8869 3.64146C7.8869 4.94472 6.80698 6.00122 5.47482 6.00122C4.14266 6.00122 3.06274 4.94472 3.06274 3.64146C3.06274 2.33819 4.14266 1.28169 5.47482 1.28169ZM10.9496 9.13341C10.9496 8.77948 10.6564 8.49256 10.2946 8.49256H0.655051C0.293276 8.49256 0 8.77948 0 9.13341L0.00490631 9.44283C0.0865017 11.9957 1.18142 13.9085 2.95869 15.0774L3.06664 15.1456L3.06713 20.3592C3.06713 20.7131 3.3604 21 3.72218 21H7.22746L7.32426 20.9931C7.64014 20.9473 7.88251 20.6809 7.88251 20.3592L7.88177 15.1456L7.99101 15.0772C9.8391 13.8613 10.9496 11.8411 10.9496 9.13341ZM9.61312 9.77338L9.59562 9.98296C9.38238 11.9801 8.40387 13.3938 6.90333 14.2297L6.82058 14.2843C6.66523 14.4048 6.57241 14.5892 6.57241 14.7866L6.57167 19.7183H4.37675L4.37723 14.7866C4.37723 14.5562 4.25084 14.3436 4.04618 14.2296L3.84481 14.1121C2.45815 13.2644 1.55751 11.8897 1.35401 9.98311L1.3353 9.77338H9.61312ZM20.3449 0.857318C20.6738 0.857318 20.9461 1.09444 20.9929 1.40346L21 1.49816V12.6433C21 12.965 20.7576 13.2314 20.4417 13.2772L20.3449 13.2841H12.0199C11.6581 13.2841 11.3648 12.9972 11.3648 12.6433C11.3648 12.3215 11.6072 12.0552 11.9231 12.0094L12.0199 12.0024L19.6898 12.0015V2.13845L11.1436 2.13901C10.8147 2.13901 10.5424 1.90189 10.4956 1.59286L10.4885 1.49816C10.4885 1.17641 10.7309 0.910038 11.0468 0.864266L11.1436 0.857318H20.3449ZM18.8928 4.33589C18.8928 3.98196 18.5995 3.69504 18.2378 3.69504H12.6163L12.5195 3.70199C12.2037 3.74776 11.9613 4.01413 11.9613 4.33589C11.9613 4.68981 12.2546 4.97673 12.6163 4.97673H18.2378L18.3346 4.96978C18.6504 4.92401 18.8928 4.65764 18.8928 4.33589ZM18.2378 6.26699C18.5995 6.26699 18.8928 6.55391 18.8928 6.90784C18.8928 7.22959 18.6504 7.49596 18.3346 7.54173L18.2378 7.54868H14.369C14.0072 7.54868 13.7139 7.26177 13.7139 6.90784C13.7139 6.58608 13.9563 6.31971 14.2722 6.27394L14.369 6.26699H18.2378ZM18.8928 9.47979C18.8928 9.12586 18.5995 8.83895 18.2378 8.83895H16.1216L16.0248 8.84589C15.7089 8.89167 15.4666 9.15804 15.4666 9.47979C15.4666 9.83372 15.7598 10.1206 16.1216 10.1206H18.2378L18.3346 10.1137C18.6504 10.0679 18.8928 9.80155 18.8928 9.47979Z" /></svg>'
                );
                info.el.innerHTML = info.el.innerHTML.replace(
                  '$CAT',
                  '<svg _ngcontent-drh-c240="" _ngcontent-ygw-c83="" viewBox="0 0 25 25 " fill="none " xmlns="http://www.w3.org/2000/svg " class="strock st-fill"><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" fill-rule="evenodd " clip-rule="evenodd " d="M17.159 22.5804L14.1838 23.6601L14.8389 20.5636L20.8901 13.6026L23.2101 15.6193L17.159 22.5804Z " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M8.76697 6.96094L6.28636 9.56458L4.86914 8.26276 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M9.32686 22.5217H2C1.44771 22.5217 1 22.074 1 21.5217V2C1 1.44772 1.44772 1 2 1L14.7946 1L18.9348 4.79795V9.96715 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M8.76697 12.2871L6.28636 14.8908L4.86914 13.5889 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M11.9404 14.0978H14.4013 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path><path _ngcontent-drh-c240="" _ngcontent-ygw-c83="" d="M11.9404 8.77165H14.4013 " stroke="#766DAA " stroke-width="1.4 " stroke-linecap="round " stroke-linejoin="round "></path></svg>'
                );
              },
            }).render();
          } else {
            if (eventData.length > 0) {
              let defaultDate =
                eventData.length > 1
                  ? new Date(eventData[1].start)
                  : new Date(eventData[0].start);
              let calendarElHome: HTMLElement = document.getElementById(
                'homecalendar' + (i + 1)
              );
              let me = this;
              new Calendar(calendarElHome, {
                plugins: [],
                defaultView:
                  window.innerWidth > 768 ? 'agendaWeek' : 'agendaDay',
                defaultDate: defaultDate,
                editable: false,
                eventLimit: 2,
                events: HomeeventData,
                allDaySlot: false,
                eventOverlap: false,
                columnHeaderFormat: {
                  weekday: 'short',
                  month: 'short',
                  day: 'numeric',
                },
                displayEventTime: true,
                eventTimeFormat: {
                  hour: 'numeric',
                  minute: '2-digit',
                  meridiem: 'short',
                },
                buttonText: {
                  today: 'Today',
                },
                header: false,
                columnHeader: false,
                minTime: { hours: 0 },
                maxTime: { hours: 0, seconds: 1 },

                slotDuration: {
                  minute: 1,
                },
              }).render();
            }
          }
          if (eventData.length > 0 || HomeeventData.length > 0) {
            this.HomeworkMainWeekData[i].numberWeek = 'WEEK' + number;
            number++;
          } else {
            let calendarElHome: HTMLElement = document.getElementById(
              'week' + (i + 1)
            );
            calendarElHome.setAttribute('class', 'displaynon');
          }
        }
      }, 100);
    }
  }
  weekset() {
    var weekfilter = [];
    var secondarray = [];
    this.MainWeekData.forEach((x) => {
      if (weekfilter.length <= 0) {
        var setdata = x.filter(
          (y) => y.Date > '0' && y.ScheduleData.length > 0
        );
        if (setdata.length > 0) {
          weekfilter.push(x);
          secondarray.push(x);
          return;
        }
      } else {
        secondarray.push(x);
      }
    });
    this.MainWeekData = secondarray;
  }
  async getExpiryDate() {
    let expirySharedData = this.sharedDataService.getExpiryDateData()
    if (expirySharedData && expirySharedData.length > 0) {
      this.ExpiryDate = expirySharedData[0].expiry_date;
      this.HeaderStartDate = expirySharedData[0].createdAt;
      setTimeout(() => {
        this.service.title = '';
        this.service.title =
          "<p class='HeaderUser'><span>Course Schedule</span></p>";
        this.service.DateSchdule =
          "<p class='HeaderUser'><span>Course Schedule</span></p>";
      }, 100);
    } 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
          var userId = localStorage.getItem('CisspUserId');
          var cohort_id = localStorage.getItem('cohort_id');
          var course_type = localStorage.getItem('course_type');
          var method_id = localStorage.getItem('method');
          await this.ScheduleserviceService.getExpiryDate(
            userId,
            course_type,
            cohort_id,
            method_id,
            token
          ).then((data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              if (list.data.length > 0) {
                this.sharedDataService.setExpiryDateData(list.data)
                this.ExpiryDate = list.data[0].expiry_date;
                this.HeaderStartDate = list.data[0].createdAt;
              }
              setTimeout(() => {
                this.service.title = '';
                this.service.title = "<p class='HeaderUser'><span>Course Schedule</span></p>";
                this.service.DateSchdule = "<p class='HeaderUser'><span>Course Schedule</span></p>";
              }, 100);
            }
          });
        }
      });
    }
  }
  async ngOnInit() {
    sessionStorage.setItem('clearInterval', 'true');
    await this.SocketConnect();
    let me = this;
    setTimeout(() => {
      me.socket.OnMessage().subscribe(async (result) => {
        let data = JSON.parse(result);
        if (data.message != undefined) {
          if (data.message == 'Next Question.') {
            me.ScheduleList = [];
            me.EventData = [];
            me.WeekData = [];
            me.MainWeekData = [];
            me.AssignMainWeekData = [];
            me.HomeworkMainWeekData = [];
            me.bkpScheduleList = [];
            me.calScheduleList = [];
            me.bkpSelfScheduleList = [];
            me.resetDatalist = [];
            await me.getExpiryDate();
            await me.getSelfSchedule(0);
            await me.scduledataall();
            await me.BaselineData();
          }
        }
      });
    }, 1000);
    momentZone.tz.setDefault(this.timezone);
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: true,
      CATresult: false,
      CATQue: false,
      knowques: false,
      knowresult: false,
      PracticeResult: false,
      studentprofile: false,
      Practiceques: false,
      resource: false,
      liveSupport: false,
    };
    await this.getAllComponentTime();
    await this.getNextLiveCall();
    await this.getExpiryDate();
    await this.getSelfSchedule(0);
    await this.scduledataall();
    await this.BaselineData();
    await this.disablePresetOption();
    await this.getEventRecording();
    this.ScheduleList.forEach(async (element) => {
      if (
        (element.type == 'KA' || element.type == 'PRACTICE') &&
        element.status == 'Completed'
      ) {
        var bar = new Promise(async (resolve, reject) => {
          this.Summery = true;
          await this.ViewSummery(element);
        });
        bar.then(async () => {
          this.Summery = false;
        });
      }
    });
    setTimeout(() => {
      this.Summery = false;
    }, 6000);
    if (this.IsSelfPacedClass) {
      this.List();
    } else {
      // this.Weekly();
      this.List();
    }
  }
  matpaginator() {
    const note = document.querySelector('.mat-select-panel') as HTMLElement;
    note.style.backgroundColor = 'yellow';
  }
  groupByArray(array, key) {
    return array.reduce((hash, obj) => {
      if (obj[key] === undefined) return hash;
      return Object.assign(hash, {
        [obj[key]]: (hash[obj[key]] || []).concat(obj),
      });
    }, {});
  }
  async getEventRecording() {
    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
        this.spinner.show();
        var cohort_id = localStorage.getItem('cohort_id');
        var course_type = localStorage.getItem('course_type');
        var method = localStorage.getItem('method');
        if (method == '0') {
          course_type = 'live';
        }
        let request = {
          cohort_id: cohort_id,
          method_type: course_type,
        };
        await this.videoService
          .getEventRecording(request, token)
          .then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              var users: supportList[] = [];
              list.data.forEach((element) => {
                let play_list = element.play_list;
                let src_list = [];
                if (play_list) {
                  let play = JSON.parse(play_list);
                  if (play.length > 0) {
                    src_list = play;
                  }
                }
                if (src_list.length > 0) {
                  src_list.forEach((src) => {
                    src.src = element.meeting_id + '/audio/' + src.src;
                  });
                }
                if (element.recording_url != null) {
                  users.push({
                    certi_id: element.certi_id,
                    duration: Math.ceil(element.duration / 60),
                    event_id: element.event_id,
                    id: element.id,
                    meeting_id: element.meeting_id,
                    play_list: src_list,
                    title: element.title,
                    createdAt: element.createdAt,
                    recording_url: element.recording_url,
                    questions: JSON.parse(element.questions)
                  });
                }
              });
              this.recordingsData = users.reverse();
              this.dataSource = new MatTableDataSource(users);
              this.dataSource.paginator = this.paginator;
              this.pagination = true;
            }
          });
        this.spinner.hide();
      }
    });
  }
  tabExpand() {
    document.getElementById('tabExpandOpen').classList.toggle('tabExpandActive');
    document.getElementById('tabSection').classList.toggle('history-main-tab-open');
  }
  async getNextLiveCall() {
    this.spinner.show();
    this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        this.spinner.show();
        var cohort_id = localStorage.getItem('cohort_id');
        var user_id = localStorage.getItem('CisspUserId');
        await this.service
          .getNextLiveCall(cohort_id, user_id, token)
          .then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              let schedule_data = list.data;
              let upcomingLiveCall: upcomingEventDetail[] = JSON.parse(JSON.stringify(schedule_data)).filter(event => event.status == "Not Started");
              schedule_data.sort(
                (a, b) =>
                  new Date(a.due_date).getTime() -
                  new Date(b.due_date).getTime()
              );
              let running = schedule_data.filter(
                (x) => x.is_live == 1 && x.event_url != '#' && x.event_url != ''
              );
              if (running.length > 0) {
                this.showJoinButton = true;
                this.nextLiveCall = running[0];
                let timeZone = running[0].due_date.substr(running[0].due_date.length - 6, 6);
                let due_date: Date;
                let currTimeZone = this.auth.currentTimeZone();
                if (currTimeZone.timeValue == timeZone) {
                  due_date = new Date(running[0].due_date);
                } else {
                  due_date = new Date(new Date(running[0].due_date).toLocaleString('en-US', { timeZone: this.timezoneLive.nameValue }));
                }
                this.nextLiveCall['due_date'] = due_date;
                this.nextLiveCall['ev_date'] =
                  this.dayNames[due_date.getDay()] +
                  ' ' +
                  this.monthsNames[due_date.getMonth()] +
                  ' ' +
                  due_date.getDate() +
                  ' at ' +
                  due_date.toLocaleTimeString('en-US', {
                    hour: 'numeric',
                    minute: 'numeric',
                    hour12: true,
                  }) +
                  ' ' +
                  this.timezoneLive.abbr;
              } else {
                for (let i = 0; i < schedule_data.length; i++) {
                  schedule_data[i]['end_date'] =
                    schedule_data[i].due_date.toString().substr(0, 11) +
                    schedule_data[i].end_time +
                    schedule_data[i].due_date
                      .toString()
                      .substr(16, schedule_data[i].due_date.length);
                  let due_date: Date;
                  let end_date: Date;
                  let overdue_date;
                  due_date = new Date(
                    new Date(schedule_data[i].due_date).toLocaleString(
                      'en-US',
                      { timeZone: this.timezoneLive.nameValue }
                    )
                  );
                  end_date = new Date(
                    new Date(schedule_data[i].end_date).toLocaleString(
                      'en-US',
                      { timeZone: this.timezoneLive.nameValue }
                    )
                  );
                  let due =
                    schedule_data[i].due_date.split('T')[0] +
                    'T' +
                    schedule_data[i].end_time +
                    ':' +
                    schedule_data[i].due_date.split(':')[2] +
                    schedule_data[i].due_date.split(':')[3];
                  overdue_date = new Date(
                    new Date(due).toLocaleString('en-US', {
                      timeZone: this.timezoneLive.nameValue,
                    })
                  );
                  let curr_date = new Date(
                    new Date().toLocaleString('en-US', {
                      timeZone: this.timezoneLive.nameValue,
                    })
                  );
                  if (overdue_date.getTime() >= curr_date.getTime()) {
                    if (schedule_data[i].is_live == 1) {
                      this.showJoinButton = true;
                      this.isBefore15 = false;
                      this.nextLiveCall = schedule_data[i];
                      this.nextLiveCall['due_date'] = due_date;
                      this.nextLiveCall['end_date'] = end_date;
                      let dt = new Date(this.nextLiveCall.due_date);
                      this.nextLiveCall['ev_date'] =
                        this.dayNames[dt.getDay()] +
                        ' ' +
                        this.monthsNames[dt.getMonth()] +
                        ' ' +
                        dt.getDate() +
                        ' at ' +
                        dt.toLocaleTimeString('en-US', {
                          hour: 'numeric',
                          minute: 'numeric',
                          hour12: true,
                        }) +
                        ' ' +
                        this.timezoneLive.abbr;
                    } else {
                      let before15Date = new Date(
                        new Date(due_date).setMinutes(
                          new Date(due_date).getMinutes() - 15
                        )
                      );
                      if (before15Date <= curr_date) {
                        this.isBefore15 = true;
                        this.showJoinButton = true;
                        this.nextLiveCall = schedule_data[i];
                        this.nextLiveCall['due_date'] = due_date;
                        this.nextLiveCall['end_date'] = end_date;
                        let dt = new Date(this.nextLiveCall.due_date);
                        this.nextLiveCall['ev_date'] =
                          this.dayNames[dt.getDay()] +
                          ' ' +
                          this.monthsNames[dt.getMonth()] +
                          ' ' +
                          dt.getDate() +
                          ' at ' +
                          dt.toLocaleTimeString('en-US', {
                            hour: 'numeric',
                            minute: 'numeric',
                            hour12: true,
                          }) +
                          ' ' +
                          this.timezoneLive.abbr;
                      } else {
                        this.isBefore15 = false;
                        this.showJoinButton = false;
                        this.nextLiveCall = schedule_data[i];
                        this.nextLiveCall['due_date'] = due_date;
                        this.nextLiveCall['end_date'] = end_date;
                        let dt = new Date(this.nextLiveCall.due_date);
                        this.nextLiveCall['ev_date'] =
                          this.dayNames[dt.getDay()] +
                          ' ' +
                          this.monthsNames[dt.getMonth()] +
                          ' ' +
                          dt.getDate() +
                          ' at ' +
                          dt.toLocaleTimeString('en-US', {
                            hour: 'numeric',
                            minute: 'numeric',
                            hour12: true,
                          }) +
                          ' ' +
                          this.timezoneLive.abbr;
                      }
                      let timeUntilTarget = before15Date.getTime() - curr_date.getTime() + 10000;
                      if (timeUntilTarget > 0) {
                        setTimeout(async () => {
                          this.showJoinButton = true;
                          this.getNextLiveCall()
                        }, timeUntilTarget)
                      }
                    }
                    break;
                  }
                }
              }
              // upcominglivecall start
              for (let i = 0; i < upcomingLiveCall.length; i++) {
                upcomingLiveCall[i]['end_date'] =
                  upcomingLiveCall[i].due_date.toString().substr(0, 11) +
                  upcomingLiveCall[i].end_time +
                  upcomingLiveCall[i].due_date
                    .toString()
                    .substr(16, upcomingLiveCall[i].due_date.length);
                let due_date: Date;
                let end_date: Date;
                let overdue_date;
                due_date = new Date(
                  new Date(upcomingLiveCall[i].due_date).toLocaleString(
                    'en-US',
                    { timeZone: this.timezoneLive.nameValue }
                  )
                );
                end_date = new Date(
                  new Date(upcomingLiveCall[i].end_date).toLocaleString(
                    'en-US',
                    { timeZone: this.timezoneLive.nameValue }
                  )
                );
                let due =
                  upcomingLiveCall[i].due_date.split('T')[0] +
                  'T' +
                  upcomingLiveCall[i].end_time +
                  ':' +
                  upcomingLiveCall[i].due_date.split(':')[2] +
                  upcomingLiveCall[i].due_date.split(':')[3];
                overdue_date = new Date(
                  new Date(due).toLocaleString('en-US', {
                    timeZone: this.timezoneLive.nameValue,
                  })
                );
                let curr_date = new Date(
                  new Date().toLocaleString('en-US', {
                    timeZone: this.timezoneLive.nameValue,
                  })
                );
                if (overdue_date.getTime() >= curr_date.getTime()) {
                  let before15Date = new Date(
                    new Date(due_date).setMinutes(
                      new Date(due_date).getMinutes() - 15
                    )
                  );
                  if (before15Date <= curr_date) {
                    this.isBefore15 = true;
                    this.upcomingCall = schedule_data[i];
                    this.upcomingCall['due_date'] = due_date;
                    this.upcomingCall['end_date'] = end_date;
                    let dt = new Date(this.upcomingCall.due_date);
                    this.upcomingCall['ev_date'] =
                      this.dayNames[dt.getDay()] +
                      ' ' +
                      this.monthsNames[dt.getMonth()] +
                      ' ' +
                      dt.getDate() +
                      ' at ' +
                      dt.toLocaleTimeString('en-US', {
                        hour: 'numeric',
                        minute: 'numeric',
                        hour12: true,
                      }) +
                      ' ' +
                      this.timezoneLive.abbr;
                  } else {
                    this.isBefore15 = false;
                    this.upcomingCall = upcomingLiveCall[i];
                    this.upcomingCall['due_date'] = due_date;
                    this.upcomingCall['end_date'] = end_date;
                    let dt = new Date(this.upcomingCall.due_date);
                    this.upcomingCall['ev_date'] =
                      this.dayNames[dt.getDay()] +
                      ' ' +
                      this.monthsNames[dt.getMonth()] +
                      ' ' +
                      dt.getDate() +
                      ' at ' +
                      dt.toLocaleTimeString('en-US', {
                        hour: 'numeric',
                        minute: 'numeric',
                        hour12: true,
                      }) +
                      ' ' +
                      this.timezoneLive.abbr;
                  }
                }
              }
              this.upcomingLiveCall = upcomingLiveCall.filter((event) => event.id !== this.nextLiveCall.id);;
              this.upcomingEventList = new MatTableDataSource(this.upcomingLiveCall);
              this.upcomingEventList.paginator = this.paginator;
              if (this.nextLiveCall == null || this.nextLiveCall == undefined) {
                this.noEvent = true;
              } else {
                this.noEvent = false;
              }
            }
          });
        this.spinner.hide();
      }
    });
  }
  playVideoPopup(item: any) {
    var eventinfo = btoa(JSON.stringify(item.event_id));
    this.router.navigate([`/eventrecordings/${eventinfo}`]);
  }
  joinMeeting() {
    if(!this.nextLiveCall.event_url){
      var eventstart = {
        id: this.nextLiveCall.id,
        title: this.nextLiveCall.examname,
        user_id: localStorage.getItem('CisspUserId'),
      };
      let meet_url = btoa(JSON.stringify(eventstart));
      meet_url = encodeURIComponent(meet_url);
      // this.router.navigate([`startconference/${meet_url}`]);
      this.router.navigate([`conference/${meet_url}`]);
    }else{
      window.open(this.nextLiveCall.event_url, '_blank');
    }
  }

  popupCloseSM() {
    var element = document.getElementById('popup-close');
    element.classList.toggle('popup-opencal-open');
  }
  calendarForLive(type) {
    let data = JSON.parse(this.nextLiveCall.repeat_on);
    let weekdays = data
      .filter((item) => item.value === 1)
      .map((item) => {
        const dayName = item.name.slice(0, 2).toUpperCase();
        return dayName;
      });
    let options: CalendarOptions;
    if (this.nextLiveCall.repeat_type == 'Week') {
      if (this.nextLiveCall.ends_type == 'Never') {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            weekdays: weekdays,
          },
        };
      } else {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            weekdays: weekdays,
            end: new Date(this.nextLiveCall.ends_on),
          },
        };
      }
    } else if (
      this.nextLiveCall.repeat_type == '' ||
      this.nextLiveCall.repeat_type == null
    ) {
      options = {
        title: this.nextLiveCall.examname,
        description: this.nextLiveCall.examname,
        start: new Date(this.nextLiveCall.due_date),
        end: new Date(this.nextLiveCall.end_date),
      };
    } else {
      if (this.nextLiveCall.ends_type == 'Never') {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
          },
        };
      } else if (this.nextLiveCall.ends_type == 'After') {
        let end_on = new Date(this.nextLiveCall.ends_on);
        end_on.setDate(end_on.getDate() + 1);
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            end: new Date(end_on),
          },
        };
      } else {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            end: new Date(this.nextLiveCall.ends_on),
          },
        };
      }
    }
    if (type == 'g') {
      const googleCalendar = new GoogleCalendar(options);
      window.open(googleCalendar.render());
    }
    if (type == 'o') {
      if (this.nextLiveCall.repeat_count == 0) {
        const outlookcalendar = new OutlookCalendar(options);
        window.open(outlookcalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(this.nextLiveCall.examname + '.ics');
      }
    }
    if (type == 'y') {
      if (this.nextLiveCall.repeat_count == 0) {
        const yahoocalendar = new YahooCalendar(options);
        window.open(yahoocalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(this.nextLiveCall.examname + '.ics');
      }
    }
    if (type == 'o3') {
      if (this.nextLiveCall.repeat_count == 0) {
        const outlookcalendar = new OutlookCalendar(options);
        window.open(outlookcalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(this.nextLiveCall.examname + '.ics');
      }
    }
    if (type == 'i') {
      const icalendar = new ICalendar(options);
      icalendar.download(this.nextLiveCall.examname + '.ics');
    }
  }
  calendarForUpcomingEvent(type, element) {
    let data = JSON.parse(element.repeat_on);
    let weekdays = data
      .filter((item) => item.value === 1)
      .map((item) => {
        const dayName = item.name.slice(0, 2).toUpperCase();
        return dayName;
      });
    let options: CalendarOptions;
    if (element.repeat_type == 'Week') {
      if (element.ends_type == 'Never') {
        options = {
          title: element.examname,
          description: element.examname,
          start: new Date(element.due_date),
          end: new Date(element.end_date),
          recurrence: {
            frequency:
              element.repeat_type == 'Day'
                ? 'DAILY'
                : element.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : element.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: element.repeat_count,
            weekdays: weekdays,
          },
        };
      } else {
        options = {
          title: element.examname,
          description: element.examname,
          start: new Date(element.due_date),
          end: new Date(element.end_date),
          recurrence: {
            frequency:
              element.repeat_type == 'Day'
                ? 'DAILY'
                : element.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : element.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: element.repeat_count,
            weekdays: weekdays,
            end: new Date(element.ends_on),
          },
        };
      }
    } else if (
      element.repeat_type == '' ||
      element.repeat_type == null
    ) {
      options = {
        title: element.examname,
        description: element.examname,
        start: new Date(element.due_date),
        end: new Date(element.end_date),
      };
    } else {
      if (element.ends_type == 'Never') {
        options = {
          title: element.examname,
          description: element.examname,
          start: new Date(element.due_date),
          end: new Date(element.end_date),
          recurrence: {
            frequency:
              element.repeat_type == 'Day'
                ? 'DAILY'
                : element.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : element.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: element.repeat_count,
          },
        };
      } else if (element.ends_type == 'After') {
        let end_on = new Date(element.ends_on);
        end_on.setDate(end_on.getDate() + 1);
        options = {
          title: element.examname,
          description: element.examname,
          start: new Date(element.due_date),
          end: new Date(element.end_date),
          recurrence: {
            frequency:
              element.repeat_type == 'Day'
                ? 'DAILY'
                : element.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : element.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: element.repeat_count,
            end: new Date(end_on),
          },
        };
      } else {
        options = {
          title: element.examname,
          description: element.examname,
          start: new Date(element.due_date),
          end: new Date(element.end_date),
          recurrence: {
            frequency:
              element.repeat_type == 'Day'
                ? 'DAILY'
                : element.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : element.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: element.repeat_count,
            end: new Date(element.ends_on),
          },
        };
      }
    }
    if (type == 'g') {
      const googleCalendar = new GoogleCalendar(options);
      window.open(googleCalendar.render());
    }
    if (type == 'o') {
      if (element.repeat_count == 0) {
        const outlookcalendar = new OutlookCalendar(options);
        window.open(outlookcalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(element.examname + '.ics');
      }
    }
    if (type == 'y') {
      if (element.repeat_count == 0) {
        const yahoocalendar = new YahooCalendar(options);
        window.open(yahoocalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(element.examname + '.ics');
      }
    }
    if (type == 'o3') {
      if (element.repeat_count == 0) {
        const outlookcalendar = new OutlookCalendar(options);
        window.open(outlookcalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(element.examname + '.ics');
      }
    }
    if (type == 'i') {
      const icalendar = new ICalendar(options);
      icalendar.download(element.examname + '.ics');
    }
  }
  SaveScheduleList() {
    let Scheduledata = [];
    var userId = localStorage.getItem('CisspUserId');
    var cohort_id = localStorage.getItem('cohort_id');
    var userdetails = JSON.parse(localStorage.getItem('userdetails'));
    this.ScheduleList.forEach((element) => {
      Scheduledata.push({
        type:
          element.type == 'VideoLesson'
            ? 'video'
            : element.type == 'MindMap'
              ? 'mindmap'
              : element.type,
        cohort_id: cohort_id,
        type_id: element.id,
        due_date: this.auth.ConvertDateDDFormat(
          element.due_date,
          this.timezone,
          'YYYY-MM-DD'
        ),
        overdue_date: this.auth.ConvertDateDDFormat(
          element.overdue_date,
          this.timezone,
          'YYYY-MM-DD'
        ),
        exam_name: element.examname,
        cohort_name: '',
        email: userdetails.email,
        user_id: userId,
        is_completed: element.status == 'Completed' ? 1 : 0,
      });
    });
    this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.router.navigate(['/login']);
      } else {
        var token = session
        this.ScheduleserviceService.SaveSelfpacedUserData(
          Scheduledata,
          token
        ).then(async (data) => { });
      }
    });
  }
  async SocketConnect() {
    var userId = parseInt(localStorage.getItem('CisspUserId'));
    let MessageArr = {
      action: 'message',
      msg: {
        action: 'connected',
        user_id: userId,
        test_id: 1,
        roll_id: 3,
        q_id: 1,
        sr_no: 1,
      },
    };
    this.socket.Connect();
    this.socket
      .OnOpen()
      .then((result) => {
        this.socket
          .DoSend(MessageArr)
          .then((result) => { })
          .catch((err) => { });
      })
      .catch((err) => { });
  }
  formatDate(date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    return [year, month, day].join('-');
  }
  SelectCustome(custome) {
    custome = 'custome' ? (this.custome = this.custome == 1 ? 0 : 1) : '';
  }
  presetSelected(val) {
    this.sun = 1;
    this.mon = 1;
    this.tues = 1;
    this.wed = 1;
    this.thurs = 1;
    this.fri = 1;
    this.sat = 1;
    this.hsun = val;
    this.hmon = val;
    this.htues = val;
    this.hwed = val;
    this.hthurs = val;
    this.hfri = val;
    this.hsat = val;
  }
  presetUnselected(val) {
    this.sun = 0;
    this.mon = 0;
    this.tues = 0;
    this.wed = 0;
    this.thurs = 0;
    this.fri = 0;
    this.sat = 0;
    this.hsun = val;
    this.hmon = val;
    this.htues = val;
    this.hwed = val;
    this.hthurs = val;
    this.hfri = val;
    this.hsat = val;
  }
  customScheduleClick() {
    this.insane = 0;
    this.sprint = 0;
    this.balance = 0;
    this.GetOldHours();
  }
  selectOption(option) {
    this.SelfCheckBox = false;
    this.misMatchSchedule = false;
    this.ShowSuffienttime = false;
    if (option == 'balance') {
      if (!this.dis_balance) {
        if (this.balance == 1) {
          this.balance = 1;
          this.presetUnselected(0);
        } else {
          this.balance = 1;
          this.sprint = 0;
          this.insane = 0;
          this.presetSelected(2);
        }
      }
    } else if (option == 'sprint') {
      if (!this.dis_sprint) {
        if (this.sprint == 1) {
          this.sprint = 1;
          this.presetUnselected(0);
        } else {
          this.balance = 0;
          this.sprint = 1;
          this.insane = 0;
          this.presetSelected(4);
        }
      }
    } else {
      if (!this.dis_insane) {
        if (this.insane == 1) {
          this.insane = 1;
          this.presetUnselected(0);
        } else {
          this.balance = 0;
          this.sprint = 0;
          this.insane = 1;
          this.presetSelected(14);
        }
      }
    }
  }
  disablePresetOption() {
    if (this.IsSelfPacedClass) {
      let diffTime = Math.abs(
        Date.parse(new Date(this.exam_date).toDateString()) -
        Date.parse(this.study_date?.toDateString())
      );
      let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      if (diffDays < 10) {
        this.dis_balance = true;
        this.dis_sprint = true;
        this.dis_insane = true;
      } else if (diffDays < 28) {
        this.dis_balance = true;
        this.dis_sprint = true;
        this.dis_insane = false;
      } else if (diffDays < 56) {
        this.dis_balance = true;
        this.dis_sprint = false;
        this.dis_insane = false;
      } else {
        this.dis_balance = false;
        this.dis_sprint = false;
        this.dis_insane = false;
      }
    }
  }
  selectDate() {
    this.disablePresetOption();
    this.newstudy_Date = new Date(this.study_date);
    this.newstudy_Date.setDate(this.newstudy_Date.getDate() + 1);
    if (this.study_date > new Date(this.exam_date)) {
      this.ShowInvalidDate = true;
      this.misMatchSchedule = true;
    } else {
      if (
        new Date(this.exam_date) <
        new Date(this.ScheduleList[this.ScheduleList.length - 1].sortdate)
      ) {
        this.ShowSuffienttime = true;
      } else {
        this.ShowSuffienttime = false;
        this.misMatchSchedule = false;
      }
      this.ShowInvalidDate = false;
    }
    this.changeDetect.detectChanges();
  }
  selectDay(day) {
    day == 'sun'
      ? (this.sun = this.sun == 1 ? 0 : 1)
      : day == 'mon'
        ? (this.mon = this.mon == 1 ? 0 : 1)
        : day == 'tues'
          ? (this.tues = this.tues == 1 ? 0 : 1)
          : day == 'wed'
            ? (this.wed = this.wed == 1 ? 0 : 1)
            : day == 'thurs'
              ? (this.thurs = this.thurs == 1 ? 0 : 1)
              : day == 'fri'
                ? (this.fri = this.fri == 1 ? 0 : 1)
                : day == 'sat'
                  ? (this.sat = this.sat == 1 ? 0 : 1)
                  : '';
    day == 'sun'
      ? (this.hsun = this.sun == 1 ? 1 : 0)
      : day == 'mon'
        ? (this.hmon = this.mon == 1 ? 1 : 0)
        : day == 'tues'
          ? (this.htues = this.tues == 1 ? 1 : 0)
          : day == 'wed'
            ? (this.hwed = this.wed == 1 ? 1 : 0)
            : day == 'thurs'
              ? (this.hthurs = this.thurs == 1 ? 1 : 0)
              : day == 'fri'
                ? (this.hfri = this.fri == 1 ? 1 : 0)
                : day == 'sat'
                  ? (this.hsat = this.sat == 1 ? 1 : 0)
                  : '';
  }
  async getSelfSchedule(week) {
    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 userId = localStorage.getItem('CisspUserId');
        var cer_id = localStorage.getItem('CisspCourseId');
        var cohort_id = localStorage.getItem('cohort_id');
        await this.ScheduleserviceService.getSelfSchedule(
          userId,
          cer_id,
          cohort_id,
          token
        ).then((data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);

            if (list.data.length > 0 && this.IsSelfPacedClass) {
              this.CustomeTitle = 'Create your own custom schedule';
              this.IsSelfSchedule = true;
              let vals = list.data[list.data.length - 1];
              this.self_schedule_id = vals.id;
              this.sun = vals.sun;
              this.mon = vals.mon;
              this.tues = vals.tues;
              this.wed = vals.wed;
              this.thurs = vals.thurs;
              this.fri = vals.fri;
              this.sat = vals.sat;
              this.hsun = vals.hsun;
              this.hmon = vals.hmon;
              this.htues = vals.htues;
              this.hwed = vals.hwed;
              this.hthurs = vals.hthurs;
              this.hfri = vals.hfri;
              this.hsat = vals.hsat;
              this.balance = vals.btn_balance;
              this.sprint = vals.btn_sprint;
              this.insane = vals.btn_insane;
              this.exam_date = vals.exam_date ? vals.exam_date : '';
              this.study_date = vals.study_date
                ? new Date(vals.study_date)
                : undefined;
              this.newstudy_Date = new Date(this.study_date);
              this.newstudy_Date.setDate(this.newstudy_Date.getDate() + 1)
              if (
                this.hsun != 0 ||
                this.hmon != 0 ||
                this.htues != 0 ||
                this.hwed != 0 ||
                this.hthurs != 0 ||
                this.hfri != 0 ||
                this.hsat != 0
              ) {
                this.IsSelfScheduleDay = true;
              } else {
                this.IsSelfScheduleDay = false;
              }
              if (this.IsSelfSchedule && this.IsSelfScheduleDay && this.IsSelfPacedClass) {
                let hrs = 0;
                let oldDate = '';
                this.ScheduleList.forEach((sch, i) => {
                  if (i == 0 && this.IsSelfPacedClass) {
                    if (sch.type != 'title' || sch.title_type == 'Flashcard App' || sch.title_type == 'Practice Question App')
                      this.bkpScheduleList.push(this.ReArrengeArray(sch));
                  }
                  if (sch.time && sch.type != 'Events') {
                    if (oldDate == '') {
                      oldDate = this.study_date != undefined && new Date(sch.sortdate) > new Date()
                        ? new Date(this.study_date).toDateString()
                        : new Date(sch.sortdate).toDateString();
                    }
                    this.GetchangeDate(oldDate);
                    oldDate = this.GetDate;
                    let day = new Date(oldDate).getDay();
                    var noHrs = 0;
                    let noOfHrs =
                      day == 0
                        ? this.hsun
                        : day == 1
                          ? this.hmon
                          : day == 2
                            ? this.htues
                            : day == 3
                              ? this.hwed
                              : day == 4
                                ? this.hthurs
                                : day == 5
                                  ? this.hfri
                                  : day == 6
                                    ? this.hsat
                                    : 0;
                    if (sch.typeVid) {
                      hrs = hrs + (parseInt(sch.time.split(':')[0]) / 60 + sch.time.split(':')[1] / 60 / 60) * this.intervalTime;
                    } else {
                      hrs = hrs + (parseInt(sch.time.split(':')[0]) + sch.time.split(':')[1] / 60) * this.intervalTime;
                    }
                    if (oldDate != new Date(oldDate).toDateString()) {
                      hrs = 0;
                    }
                    if (hrs > noOfHrs) {
                      let oldNewDate = new Date(oldDate);
                      let oldNewdata = {
                        DateStringcompleted_date: sch.DateStringcompleted_date,
                        DateStringdue_date: new Date(oldNewDate).toDateString(),
                        DateStringoverdue_date: new Date(oldNewDate).toDateString(),
                        DateStringvalue: new Date(oldNewDate).toDateString(),
                        KA_access: sch.KA_access,
                        cohort_id: sch.cohort_id,
                        completed_date: sch.completed_date,
                        createdAt: sch.createdAt,
                        due_date: new Date(oldNewDate).toString(),
                        due_number: sch.due_number,
                        examname: sch.examname,
                        id: sch.id,
                        ketexam_name: sch.ketexam_name,
                        knowass_name: sch.knowass_name,
                        overdue_date: sch.overdue_date,
                        overdue_number: sch.overdue_number,
                        practice_name: sch.practice_name,
                        required: sch.required,
                        sortdate: new Date(oldNewDate).toString(),
                        status: sch.status,
                        time: sch.time,
                        ttlcomplete: sch.ttlcomplete,
                        ttlq: sch.ttlq,
                        ttlqpending: sch.ttlq - sch.ttlcomplete,
                        type: sch.type,
                        type_id: sch.type_id,
                        updatedAt: sch.updatedAt,
                        typeVid: sch.typeVid,
                        videolength: sch.videolength,
                        percentage: sch.percentage,
                        percentagecircle: sch.percentagecircle,
                        datelable: sch.datelable,
                        section_id: sch.section_id,
                        ProgessPer: sch.ProgessPer,
                        homework: sch.homework,
                        event_url: sch.event_url,
                        meeting_playform: sch.meeting_playform,
                        title_type: sch.title_type,
                        download_description: sch.download_description,
                        download_url: sch.download_url,
                        download_url_720p: sch.download_url_720p,
                        download_url_480p: sch.download_url_480p,
                        download_url_360p: sch.download_url_360p,
                        download_url_240p: sch.download_url_240p,
                        download_url_144p: sch.download_url_144p,
                        alreadyJoin: sch.alreadyJoin,
                      };
                      this.bkpScheduleList.push(oldNewdata);
                      this.changeDate = false;
                      let newDate = new Date(oldDate).setDate(new Date(oldDate).getDate() + 1);
                      this.GetchangeDate(new Date(newDate));
                      newDate = this.GetDate;
                      this.ScheduleList.sort((a, b) =>
                        new Date(a.due_date).getTime() - new Date(b.due_date).getTime() || a.cou - b.cou
                      );
                      oldDate = new Date(newDate).toDateString();
                      this.changeDate = false;
                      if (sch.typeVid) {
                        hrs = parseInt(sch.time.split(':')[0]) / 60 + sch.time.split(':')[1] / 60 / 60;
                      } else {
                        hrs = parseInt(sch.time.split(':')[0]) + sch.time.split(':')[1] / 60;
                      }
                    } else {
                      let newDate = new Date(oldDate);
                      let olddata = {
                        DateStringcompleted_date: sch.DateStringcompleted_date,
                        DateStringdue_date: new Date(newDate).toDateString(),
                        DateStringoverdue_date: new Date(newDate).toDateString(),
                        DateStringvalue: new Date(newDate).toDateString(),
                        KA_access: sch.KA_access,
                        cohort_id: sch.cohort_id,
                        completed_date: sch.completed_date,
                        createdAt: sch.createdAt,
                        due_date: new Date(newDate).toString(),
                        due_number: sch.due_number,
                        examname: sch.examname,
                        id: sch.id,
                        ketexam_name: sch.ketexam_name,
                        knowass_name: sch.knowass_name,
                        overdue_date: sch.overdue_date,
                        overdue_number: sch.overdue_number,
                        practice_name: sch.practice_name,
                        required: sch.required,
                        sortdate: new Date(newDate).toString(),
                        status: sch.status,
                        time: sch.time,
                        ttlcomplete: sch.ttlcomplete,
                        ttlq: sch.ttlq,
                        ttlqpending: sch.ttlq - sch.ttlcomplete,
                        type: sch.type,
                        type_id: sch.type_id,
                        updatedAt: sch.updatedAt,
                        typeVid: sch.typeVid,
                        videolength: sch.videolength,
                        percentage: sch.percentage,
                        percentagecircle: sch.percentagecircle,
                        datelable: sch.datelable,
                        section_id: sch.section_id,
                        ProgessPer: sch.ProgessPer,
                        homework: sch.homework,
                        event_url: sch.event_url,
                        meeting_playform: sch.meeting_playform,
                        title_type: sch.title_type,
                        download_description: sch.download_description,
                        download_url: sch.download_url,
                        download_url_720p: sch.download_url_720p,
                        download_url_480p: sch.download_url_480p,
                        download_url_360p: sch.download_url_360p,
                        download_url_240p: sch.download_url_240p,
                        download_url_144p: sch.download_url_144p,
                        alreadyJoin: sch.alreadyJoin,
                      };
                      this.bkpScheduleList.push(olddata);
                    }
                  } else {
                    this.bkpScheduleList.push(sch);
                  }
                  if (i == this.calScheduleList.length - 1)
                    this.enddate = new Date(oldDate);
                });
                this.ScheduleList = this.bkpScheduleList;
                if (week == 1 && !this.ShowSuffienttime) this.Weekly();
              }
            } else {
              this.CustomeTitle = 'Create your own custom schedule';
              this.IsSelfSchedule = false;
              var usr = localStorage.getItem('userdetails');
              var dates = JSON.parse(<string>usr);
              this.exam_date = '';
              this.study_date = undefined;
              this.aliasname = dates.aliasname;
              this.name = dates.name;
            }
          }
        });
      }
      this.spinner.hide();
    });
  }
  async generateSelfSchedule() {
    this.intervalTime = 0;
    let diffTime = Math.abs(Date.parse(new Date(this.exam_date).toDateString()) - Date.parse(this.startdate.toDateString()));
    let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    if (
      this.IsSelfSchedule &&
      this.IsSelfScheduleDay &&
      this.IsSelfPacedClass
    ) {
      let getDateSet = new Date(this.startdate).toDateString();
      let day = new Date(getDateSet).getDay();
      let noHrs = 0;
      let CountHrs = 0;
      for (let i = 0; i < diffDays; i++) {
        noHrs =
          day == 0
            ? this.hsun
            : day == 1
              ? this.hmon
              : day == 2
                ? this.htues
                : day == 3
                  ? this.hwed
                  : day == 4
                    ? this.hthurs
                    : day == 5
                      ? this.hfri
                      : day == 6
                        ? this.hsat
                        : 0;
        if (noHrs != 0) {
          CountHrs = CountHrs + noHrs;
        }
        getDateSet = new Date(
          new Date(getDateSet).setDate(new Date(getDateSet).getDate() + 1)
        ).toDateString();
        day = new Date(getDateSet).getDay();
      }
      this.SelfScheduleTime = CountHrs * 60;
    } else {
      this.SelfScheduleTime = this.isNotSelfSchedualTime * diffDays;
    }
    if (this.SelfScheduleTime > this.ErrorSelfSchedule) {
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = session
          var userId = localStorage.getItem('CisspUserId');
          var cohort_id = localStorage.getItem('cohort_id');
          var cer_id = localStorage.getItem('CisspCourseId');
          await this.spinner.show();
          await this.ScheduleserviceService.generateSelfSchedule(
            this.self_schedule_id,
            this.IsSelfSchedule,
            parseInt(userId),
            parseInt(cer_id),
            this.exam_date,
            this.sun,
            this.mon,
            this.tues,
            this.wed,
            this.thurs,
            this.fri,
            this.sat,
            this.hsun,
            this.hmon,
            this.htues,
            this.hwed,
            this.hthurs,
            this.hfri,
            this.hsat,
            this.balance,
            this.sprint,
            this.insane,
            cohort_id,
            this.study_date,
            token
          ).then(async (data) => {
            if (data[0].status == 200) {
              // this.SelfCheckBox = false;
              this.SelfCheckBox = true;
              this.IsSelfSchedule = true;
              if (this.hsun != 0 || this.hmon != 0 || this.htues != 0 || this.hwed != 0 || this.hthurs != 0 || this.hfri != 0 || this.hsat != 0) {
                this.IsSelfScheduleDay = true;
              } else {
                this.IsSelfScheduleDay = false;
              }
              this.bkpScheduleList = [];
              this.ScheduleList = [];
              this.MainWeekData = [];
              var updateexamdata = {
                exam_date: new Date(this.exam_date).toLocaleDateString(),
                user_id: userId,
                cohort_id: cohort_id,
              };
              await this.ScheduleserviceService.updateexamdate(updateexamdata, token).then(async (data) => { });
              this.ShowSuffienttime = false;
              this.misMatchSchedule = false;
              this.UpdateSchedule = false;
              await this.scduledataall();
              // await this.Weekly(); --> change add this.List()
              await this.List();
              await this.spinner.hide();
              this.service.ShowSuccess('Successfully save schedule');
            }
          });
          await this.LoginflowService.updateUser(
            userId,
            this.name,
            this.aliasname,
            this.exam_date,
            token
          );
        }
      });
    } else {
      this.ShowSuffienttime = true;
      this.misMatchSchedule = true;
      this.UpdateSchedule = true;
    }
  }
  showSchedule(ScheduleShow) {
    this.isShowSchedule = true;
    this.selected_schedule = ScheduleShow;
    if (ScheduleShow.type == 'KA') {
      this.exam_name = ScheduleShow.examname + ' Knowledge Assessment';
    } else if (ScheduleShow.type == 'CAT') {
      this.exam_name = ScheduleShow.examname + ' CAT Exam';
    } else if (ScheduleShow.type == 'PRACTICE') {
      this.exam_name = ScheduleShow.examname + ' Practice Test';
    } else {
      this.exam_name = ScheduleShow.examname;
    }
    this.exam_button = ScheduleShow.status;
  }
  async datesort() {
    var date = this.startdate;
    var enddate = this.enddate;
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(enddate.getFullYear(), date.getMonth() + 1, 0);
    let month = date.getMonth();
    let endmonth = enddate.getMonth();
    let f = this.getOrdinal(firstDay.getDate());
    let l = this.getOrdinal(lastDay.getDate());
    setTimeout(() => {
      this.service.title = '';
      this.service.title = "<p class='HeaderUser'><span>Detailed</span> Schedule <span>(" + this.months[month] + ' ' + f + ' - ' + this.months[endmonth] + ' ' + l + ')</span></p>';
      this.service.DateSchdule = "<p class='HeaderUser'><span>Detailed</span> Schedule <span>(" + this.months[month] + ' ' + f + ' - ' + this.months[endmonth] + ' ' + l + ')</span></p>';
    }, 100);
    await this.spinner.show();
    this.MainWeekData = [];
    await this.createWeekly();
    await this.weekset();
    await this.spinner.hide();
  }
  async selfPacedAfterApiCall(scheduleData: any) {
    this.sharedDataService.setScheduleData(scheduleData)
    this.calScheduleList = [];
    this.calScheduleList = scheduleData;
    this.bkpScheduleList = [];
    this.ScheduleList = [];
    this.bkpSelfScheduleList = [];
    this.SelfScheduleArray();
    this.GetCalTime();
    if (this.calScheduleList && this.calScheduleList.length > 0) {
      this.calScheduleList.sort(
        (a, b) =>
          new Date(a.due_date).getTime() -
          new Date(b.due_date).getTime() || a.cou - b.cou
      );
      this.calScheduleList.forEach((element, i) => {
        if (element.due_date) {
          if (i == 0)
            this.startdate = this.study_date != undefined ? new Date(this.study_date) : new Date(element.due_date);
          if (i == this.calScheduleList.length - 1)
            this.enddate = new Date(element.due_date);
          if (element.status != 'Completed') {
            var CurrentDate = momentZone.parseZone(new Date()).local(true).toDate();
            var startExamdate = new Date(element.due_date);
            var StartExam_Dt =
              startExamdate.getTime() - CurrentDate.getTime();
            var StartDateDay =
              Math.floor(StartExam_Dt / (1000 * 60 * 60 * 24)) + 1;
            if (StartDateDay <= 0) {
              element['DateStringvalue'] = '';
              if (element.createdAt) {
                element['DateStringvalue'] = new Date(element.createdAt).toDateString();
              }
              element['DateStringdue_date'] = '';
              if (element.due_date) {
                element['DateStringdue_date'] = new Date(element.due_date).toDateString();
              }
              element['DateStringoverdue_date'] = '';
              if (element.overdue_date) {
                element['DateStringoverdue_date'] = new Date(element.overdue_date).toDateString();
              }
              element['DateStringcompleted_date'] = '';
              if (element.completed_date) {
                element['DateStringcompleted_date'] = new Date(element.completed_date).toDateString();
              }
            } else {
              element['DateStringvalue'] = '';
              if (element.due_date) {
                element['DateStringvalue'] = new Date(element.due_date).toDateString();
              }
              element['DateStringdue_date'] = '';
              if (element.due_date) {
                element['DateStringdue_date'] = new Date(element.due_date).toDateString();
              }
              element['DateStringoverdue_date'] = '';
              if (element.overdue_date) {
                element['DateStringoverdue_date'] = new Date(element.overdue_date).toDateString();
              }
              element['DateStringcompleted_date'] = '';
              if (element.completed_date) {
                element['DateStringcompleted_date'] = new Date(element.completed_date).toDateString();
              }
            }
            element['sortdate'] = this.study_date != undefined ? new Date(this.study_date) : new Date(element.due_date);
          } else {
            element['DateStringcompleted_date'] = '';
            if (element.completed_date) {
              element['DateStringcompleted_date'] = new Date(element.completed_date).toDateString();
            }
            element['DateStringdue_date'] = '';
            if (element.due_date) {
              element['DateStringdue_date'] = new Date(element.due_date).toDateString();
            }
            element['datelable'] = 'Completed';
            element['sortdate'] = element['DateStringcompleted_date'];
          }
        }
        if (i == 0 && this.IsSelfPacedClass && !this.IsSelfSchedule) {
          if (
            element.type != 'title' ||
            element.title_type == 'Flashcard App' ||
            element.title_type == 'Practice Question App'
          )
            this.calScheduleList.unshift(this.ReArrengeArray(element));
        }
      });
      var scheduldata = this.calScheduleList.filter((x) => x.due_date);
      this.ScheduleList = scheduldata;
      if (
        this.IsSelfSchedule &&
        this.IsSelfScheduleDay &&
        this.IsSelfPacedClass
      ) {
        let hrs = 0;
        let oldDate = '';
        // revision add
        for (let i = 0; i < this.ScheduleList.length; i++) {
          if (this.ScheduleList[i].material_type == 'KA') {
            let newObj = Object.assign({}, this.ScheduleList[i], {
              material_type: 'KA_revision',
              type: 'KA_revision',
            });
            this.ScheduleList.splice(i + 1, 0, newObj);
          }
        }
        this.ScheduleList.forEach((sch, i) => {
          let myDateChange = false;
          if (i == 0 && this.IsSelfPacedClass) {
            if (
              sch.type != 'title' ||
              sch.title_type == 'Flashcard App' ||
              sch.title_type == 'Practice Question App'
            )
              this.bkpScheduleList.push(this.ReArrengeArray(sch));
          }
          if (sch.time && sch.type != 'Events') {
            if (oldDate == '') {
              oldDate =
                this.study_date != undefined
                  ? new Date(this.study_date).toDateString()
                  : new Date(sch.sortdate).toDateString();
            }
            this.GetchangeDate(oldDate);
            oldDate = this.GetDate;
            let day = new Date(oldDate).getDay();
            let noOfHrs;
            if (this.balance == 1) {
              noOfHrs = this.noOfMin / 60 / 56;
            } else if (this.sprint == 1) {
              noOfHrs = this.noOfMin / 60 / 28;
            } else if (this.insane == 1) {
              noOfHrs = this.noOfMin / 60 / 10;
            } else {
              noOfHrs =
                day == 0
                  ? this.hsun
                  : day == 1
                    ? this.hmon
                    : day == 2
                      ? this.htues
                      : day == 3
                        ? this.hwed
                        : day == 4
                          ? this.hthurs
                          : day == 5
                            ? this.hfri
                            : day == 6
                              ? this.hsat
                              : 0;
            }
            let oldhrs = hrs;
            if (sch.typeVid) {
              hrs =
                hrs +
                (parseInt(sch.time.split(':')[0]) / 60 +
                  sch.time.split(':')[1] / 60 / 60) *
                this.intervalTime;
            } else if (
              sch.material_type == 'KA' ||
              sch.material_type == 'KA_revision'
            ) {
              hrs = hrs + (parseInt(sch.time.split(':')[0]) + sch.time.split(':')[1] / 60) / 2;
            } else {
              hrs = hrs + (parseInt(sch.time.split(':')[0]) + sch.time.split(':')[1] / 60) * this.intervalTime;
            }
            if (oldDate != new Date(oldDate).toDateString()) {
              if (this.remainHours == 1) {
                hrs = hrs;
                this.remainHours = 0;
              } else {
                hrs = 0;
              }
            }
            if (
              hrs > noOfHrs && (sch.type != 'title' || sch.title_type == 'Flashcard App' || sch.title_type == 'Practice Question App')) {
              let oldNewDate = new Date(oldDate);
              let morefif = 0;
              if (hrs > noOfHrs + 0.25) {
                if (sch.typeVid) {
                  morefif = parseInt(sch.time.split(':')[0]) / 60 + sch.time.split(':')[1] / 60 / 60;
                } else if (sch.material_type == 'KA' || sch.material_type == 'KA_revision') {
                  morefif = (parseInt(sch.time.split(':')[0]) + sch.time.split(':')[1] / 60) / 2;
                } else {
                  morefif = parseInt(sch.time.split(':')[0]) + sch.time.split(':')[1] / 60;
                }
                let newDate =
                  sch.material_type == 'Test' && oldhrs == 0
                    ? new Date(oldNewDate).setDate(
                      new Date(oldNewDate).getDate()
                    )
                    : new Date(oldNewDate).setDate(
                      new Date(oldNewDate).getDate() + 1
                    );
                this.GetchangeDate(new Date(newDate));
                newDate = this.GetDate;
                if (new Date(newDate) > new Date())
                  sch['datelable'] = 'Available';
                else if (sch.status == 'Completed')
                  sch['datelable'] = 'Completed';
                else sch['datelable'] = 'Due';
                let olddata = {
                  DateStringcompleted_date:
                    sch.DateStringcompleted_date,
                  DateStringdue_date: new Date(newDate).toDateString(),
                  DateStringoverdue_date: new Date(
                    newDate
                  ).toDateString(),
                  DateStringvalue: new Date(newDate).toDateString(),
                  KA_access: sch.KA_access,
                  cohort_id: sch.cohort_id,
                  completed_date: sch.completed_date,
                  createdAt: sch.createdAt,
                  due_date: new Date(newDate).toString(),
                  due_number: sch.due_number,
                  examname: sch.examname,
                  id: sch.id,
                  ketexam_name: sch.ketexam_name,
                  knowass_name: sch.knowass_name,
                  overdue_date: sch.overdue_date,
                  overdue_number: sch.overdue_number,
                  practice_name: sch.practice_name,
                  required: sch.required,
                  sortdate: new Date(newDate).toString(),
                  status: sch.status,
                  time: sch.time,
                  ttlcomplete: sch.ttlcomplete,
                  ttlq: sch.ttlq,
                  ttlqpending: sch.ttlq - sch.ttlcomplete,
                  type: sch.type,
                  type_id: sch.type_id,
                  updatedAt: sch.updatedAt,
                  typeVid: sch.typeVid,
                  videolength: sch.videolength,
                  percentage: sch.percentage,
                  percentagecircle: sch.percentagecircle,
                  datelable: sch.datelable,
                  section_id: sch.section_id,
                  ProgessPer: sch.ProgessPer,
                  homework: sch.homework,
                  event_url: sch.event_url,
                  meeting_playform: sch.meeting_playform,
                  title_type: sch.title_type,
                  download_description: sch.download_description,
                  download_url: sch.download_url,
                  download_url_720p: sch.download_url_720p,
                  download_url_480p: sch.download_url_480p,
                  download_url_360p: sch.download_url_360p,
                  download_url_240p: sch.download_url_240p,
                  download_url_144p: sch.download_url_144p,
                  alreadyJoin: sch.alreadyJoin,
                };
                this.bkpScheduleList.push(olddata);

                if (sch.material_type == 'Test') {
                  if (new Date(newDate) > new Date())
                    sch['datelable'] = 'Available';
                  else if (sch.status == 'Completed')
                    sch['datelable'] = 'Completed';
                  else sch['datelable'] = 'Due';
                  let olddata = {
                    DateStringcompleted_date:
                      sch.DateStringcompleted_date,
                    DateStringdue_date: new Date(
                      newDate
                    ).toDateString(),
                    DateStringoverdue_date: new Date(
                      newDate
                    ).toDateString(),
                    DateStringvalue: new Date(newDate).toDateString(),
                    KA_access: sch.KA_access,
                    cohort_id: sch.cohort_id,
                    completed_date: sch.completed_date,
                    createdAt: sch.createdAt,
                    due_date: new Date(newDate).toString(),
                    due_number: sch.due_number,
                    examname: sch.examname,
                    id: sch.id,
                    ketexam_name: sch.ketexam_name,
                    knowass_name: sch.knowass_name,
                    overdue_date: sch.overdue_date,
                    overdue_number: sch.overdue_number,
                    practice_name: sch.practice_name,
                    required: sch.required,
                    sortdate: new Date(newDate).toString(),
                    status: sch.status,
                    time: sch.time,
                    ttlcomplete: sch.ttlcomplete,
                    ttlq: sch.ttlq,
                    ttlqpending: sch.ttlq - sch.ttlcomplete,
                    type: 'Test_revision',
                    type_id: sch.type_id,
                    updatedAt: sch.updatedAt,
                    typeVid: sch.typeVid,
                    videolength: sch.videolength,
                    percentage: sch.percentage,
                    percentagecircle: sch.percentagecircle,
                    datelable: sch.datelable,
                    section_id: sch.section_id,
                    ProgessPer: sch.ProgessPer,
                    homework: sch.homework,
                    event_url: sch.event_url,
                    meeting_playform: sch.meeting_playform,
                    title_type: sch.title_type,
                    download_description: sch.download_description,
                    download_url: sch.download_url,
                    download_url_720p: sch.download_url_720p,
                    download_url_480p: sch.download_url_480p,
                    download_url_360p: sch.download_url_360p,
                    download_url_240p: sch.download_url_240p,
                    download_url_144p: sch.download_url_144p,
                    alreadyJoin: sch.alreadyJoin,
                  };
                  this.bkpScheduleList.push(olddata);
                }
              } else {
                if (new Date(oldNewDate) > new Date())
                  sch['datelable'] = 'Available';
                else if (sch.status == 'Completed')
                  sch['datelable'] = 'Completed';
                else sch['datelable'] = 'Due';
                let oldNewdata = {
                  DateStringcompleted_date:
                    sch.DateStringcompleted_date,
                  DateStringdue_date: new Date(
                    oldNewDate
                  ).toDateString(),
                  DateStringoverdue_date: new Date(
                    oldNewDate
                  ).toDateString(),
                  DateStringvalue: new Date(oldNewDate).toDateString(),
                  KA_access: sch.KA_access,
                  cohort_id: sch.cohort_id,
                  completed_date: sch.completed_date,
                  createdAt: sch.createdAt,
                  due_date: new Date(oldNewDate).toString(),
                  due_number: sch.due_number,
                  examname: sch.examname,
                  id: sch.id,
                  ketexam_name: sch.ketexam_name,
                  knowass_name: sch.knowass_name,
                  overdue_date: sch.overdue_date,
                  overdue_number: sch.overdue_number,
                  practice_name: sch.practice_name,
                  required: sch.required,
                  sortdate: new Date(oldNewDate).toString(),
                  status: sch.status,
                  time: sch.time,
                  ttlcomplete: sch.ttlcomplete,
                  ttlq: sch.ttlq,
                  ttlqpending: sch.ttlq - sch.ttlcomplete,
                  type: sch.type,
                  type_id: sch.type_id,
                  updatedAt: sch.updatedAt,
                  typeVid: sch.typeVid,
                  videolength: sch.videolength,
                  percentage: sch.percentage,
                  percentagecircle: sch.percentagecircle,
                  datelable: sch.datelable,
                  section_id: sch.section_id,
                  ProgessPer: sch.ProgessPer,
                  homework: sch.homework,
                  event_url: sch.event_url,
                  meeting_playform: sch.meeting_playform,
                  title_type: sch.title_type,
                  download_description: sch.download_description,
                  download_url: sch.download_url,
                  download_url_720p: sch.download_url_720p,
                  download_url_480p: sch.download_url_480p,
                  download_url_360p: sch.download_url_360p,
                  download_url_240p: sch.download_url_240p,
                  download_url_144p: sch.download_url_144p,
                  alreadyJoin: sch.alreadyJoin,
                };
                this.bkpScheduleList.push(oldNewdata);
              }
              if (this.changeDate) {
                myDateChange = true;
              }
              this.changeDate = false;
              let newDate = new Date(oldDate).setDate(new Date(oldDate).getDate() + 1);
              this.GetchangeDate(new Date(newDate));
              newDate = this.GetDate;
              if (new Date(newDate) > new Date())
                sch['datelable'] = 'Available';
              else if (sch.status == 'Completed')
                sch['datelable'] = 'Completed';
              else sch['datelable'] = 'Due';
              this.ScheduleList.sort(
                (a, b) =>
                  new Date(a.due_date).getTime() -
                  new Date(b.due_date).getTime() || a.cou - b.cou
              );
              oldDate = new Date(newDate).toDateString();
              this.changeDate = false;
              if (sch.typeVid) {
                hrs = parseInt(sch.time.split(':')[0]) / 60 + sch.time.split(':')[1] / 60 / 60;
              } else {
                hrs = parseInt(sch.time.split(':')[0]) + sch.time.split(':')[1] / 60;
              }
              if (myDateChange) {
                if (oldhrs < noOfHrs + 0.25) {
                  hrs = morefif;
                  this.remainHours = 1;
                } else {
                  hrs = 0;
                }
              }
            } else {
              let newDate = new Date(oldDate);
              if (new Date(newDate) > new Date())
                sch['datelable'] = 'Available';
              else if (sch.status == 'Completed')
                sch['datelable'] = 'Completed';
              else sch['datelable'] = 'Due';
              let olddata = {
                DateStringcompleted_date: sch.DateStringcompleted_date,
                DateStringdue_date: new Date(newDate).toDateString(),
                DateStringoverdue_date: new Date(
                  newDate
                ).toDateString(),
                DateStringvalue: new Date(newDate).toDateString(),
                KA_access: sch.KA_access,
                cohort_id: sch.cohort_id,
                completed_date: sch.completed_date,
                createdAt: sch.createdAt,
                due_date: new Date(newDate).toString(),
                due_number: sch.due_number,
                examname: sch.examname,
                id: sch.id,
                ketexam_name: sch.ketexam_name,
                knowass_name: sch.knowass_name,
                overdue_date: sch.overdue_date,
                overdue_number: sch.overdue_number,
                practice_name: sch.practice_name,
                required: sch.required,
                sortdate: new Date(newDate).toString(),
                status: sch.status,
                time: sch.time,
                ttlcomplete: sch.ttlcomplete,
                ttlq: sch.ttlq,
                ttlqpending: sch.ttlq - sch.ttlcomplete,
                type: sch.type,
                type_id: sch.type_id,
                updatedAt: sch.updatedAt,
                typeVid: sch.typeVid,
                videolength: sch.videolength,
                percentage: sch.percentage,
                percentagecircle: sch.percentagecircle,
                datelable: sch.datelable,
                section_id: sch.section_id,
                ProgessPer: sch.ProgessPer,
                homework: sch.homework,
                event_url: sch.event_url,
                meeting_playform: sch.meeting_playform,
                title_type: sch.title_type,
                download_description: sch.download_description,
                download_url: sch.download_url,
                download_url_720p: sch.download_url_720p,
                download_url_480p: sch.download_url_480p,
                download_url_360p: sch.download_url_360p,
                download_url_240p: sch.download_url_240p,
                download_url_144p: sch.download_url_144p,
                alreadyJoin: sch.alreadyJoin,
              };
              this.bkpScheduleList.push(olddata);
              if (sch.material_type == 'Test') {
                if (new Date(newDate) > new Date())
                  sch['datelable'] = 'Available';
                else if (sch.status == 'Completed')
                  sch['datelable'] = 'Completed';
                else sch['datelable'] = 'Due';
                let olddata = {
                  DateStringcompleted_date:
                    sch.DateStringcompleted_date,
                  DateStringdue_date: new Date(newDate).toDateString(),
                  DateStringoverdue_date: new Date(
                    newDate
                  ).toDateString(),
                  DateStringvalue: new Date(newDate).toDateString(),
                  KA_access: sch.KA_access,
                  cohort_id: sch.cohort_id,
                  completed_date: sch.completed_date,
                  createdAt: sch.createdAt,
                  due_date: new Date(newDate).toString(),
                  due_number: sch.due_number,
                  examname: sch.examname,
                  id: sch.id,
                  ketexam_name: sch.ketexam_name,
                  knowass_name: sch.knowass_name,
                  overdue_date: sch.overdue_date,
                  overdue_number: sch.overdue_number,
                  practice_name: sch.practice_name,
                  required: sch.required,
                  sortdate: new Date(newDate).toString(),
                  status: sch.status,
                  time: sch.time,
                  ttlcomplete: sch.ttlcomplete,
                  ttlq: sch.ttlq,
                  ttlqpending: sch.ttlq - sch.ttlcomplete,
                  type: 'Test_revision',
                  type_id: sch.type_id,
                  updatedAt: sch.updatedAt,
                  typeVid: sch.typeVid,
                  videolength: sch.videolength,
                  percentage: sch.percentage,
                  percentagecircle: sch.percentagecircle,
                  datelable: sch.datelable,
                  section_id: sch.section_id,
                  ProgessPer: sch.ProgessPer,
                  homework: sch.homework,
                  event_url: sch.event_url,
                  meeting_playform: sch.meeting_playform,
                  title_type: sch.title_type,
                  download_description: sch.download_description,
                  download_url: sch.download_url,
                  download_url_720p: sch.download_url_720p,
                  download_url_480p: sch.download_url_480p,
                  download_url_360p: sch.download_url_360p,
                  download_url_240p: sch.download_url_240p,
                  download_url_144p: sch.download_url_144p,
                  alreadyJoin: sch.alreadyJoin,
                };
                this.bkpScheduleList.push(olddata);
              }
            }
          } else {
            this.bkpScheduleList.push(sch);
          }
          if (i == this.calScheduleList.length - 1)
            this.enddate = new Date(oldDate);
        });
        let newstudy_date = this.auth.ConvertDateDDFormat(this.study_date, this.timezone, 'YYYY-MM-DD');
        let newexam_date = this.auth.ConvertDateDDFormat(this.exam_date, this.timezone, 'YYYY-MM-DD');

        this.ScheduleList = this.bkpScheduleList.filter((item) => {
          if (item.material_type == 'Events') {
            let createdAt = this.auth.ConvertDateDDFormat(
              item.due_date,
              this.timezone,
              'YYYY-MM-DD'
            );
            return !(item.recording_url == null || !item.recording_url) && newstudy_date <= createdAt && createdAt <= newexam_date;
          } else {
            return true;
          }
        });
      }
      this.ScheduleList.sort(
        (a, b) =>
          new Date(a.due_date).getTime() -
          new Date(b.due_date).getTime() || a.cou - b.cou
      );
      let domainGroup = [];
      let currentDomain = null;
      let currentDomainArray = [];

      let startIndex = this.ScheduleList.findIndex((item) =>
        item.examname.startsWith('Material')
      );

      if (startIndex >= 0) {
        var reviewIndex = this.ScheduleList.findIndex(obj => obj.examname === "Review & Exam Strategy");
        var eventsAfterReview = this.ScheduleList.filter((obj, index) => index > reviewIndex && obj.material_type === "Events");
        eventsAfterReview.forEach((obj) => {
          obj['flashcard_PQ'] = 0;
        })
        let newScheuleList = this.ScheduleList.slice(startIndex);
        for (let item of newScheuleList) {
          if (item.title_type == 'Section' && item.examname != 'Welcome' && item.type == 'title' && item.examname.startsWith('Material')) {
            if (currentDomain != null) {
              domainGroup.push(currentDomainArray);
              currentDomainArray = [];
            }
            currentDomain = item.knowass_name;
          }
          currentDomainArray.push(item);
        }
        if (currentDomainArray.length > 0) {
          currentDomainArray.pop();
          domainGroup.push(currentDomainArray);
        }
      }
      let dateGroup = [];
      for (let domain of domainGroup) {
        domain[1]['flashcard_pqa'] = 'flashcard_pqa';
        let dateArray = domain.reduce((acc, task) => {
          let due_date;
          if (task.type == 'Events') {
            const dateArray = acc[acc.length - 1];
            due_date = dateArray.length >= 2 ? dateArray[Math.round(dateArray.length / 2)].due_date : dateArray[dateArray.length - 1].due_date;
          } else {
            due_date = task.due_date;
          }
          const existingGroup = acc.find(
            (group) => group[0].due_date === due_date
          );
          if (existingGroup) {
            existingGroup.push(task);
          } else {
            acc.push([task]);
          }
          return acc;
        }, []);
        dateGroup.push(dateArray);
      }
      for (let domain of dateGroup) {
        let array = domain[0];
        let domain_name = array[0].examname.slice(0, 8);
        domain.map((obj) => {
          let each_flashcard_day = Math.round(
            obj[0].download_description / domain.length
          );
          let each_PQA_day = Math.round(
            obj[0].download_url / domain.length
          );
          obj.map((single_obj) => {
            if (
              (typeof single_obj.download_description !== 'string' &&
                single_obj.examname != 'End of Class' && single_obj.flashcard_PQ != 0) || single_obj.title_type == 'Download'
            ) {
              single_obj['each_flashcard_day'] = each_flashcard_day;
              single_obj['each_PQA_day'] = each_PQA_day;
              single_obj['belong_to'] = domain_name;
            }
          });
        });
      }
    }
    let title_id = '';
    this.ScheduleList.forEach((element) => {
      if (element.status != 'Completed') {
        var CurrentDate = momentZone.parseZone(new Date()).local(true).toDate();
        var startExamdate = new Date(element.due_date);
        var StartExam_Dt = startExamdate.getTime() - CurrentDate.getTime();
        var StartDateDay = Math.floor(StartExam_Dt / (1000 * 60 * 60 * 24)) + 1;

        if (StartDateDay <= 0) {
          if (element.status == 'Not Started' || element.status == 'In Progress') {
            if (element.overdue_date) {
              if (this.IsSelfPacedClass) {
                element.overdue_date = new Date(new Date(element.due_date).setDate(new Date(element.due_date).getDate() + 1));
              }
              var CurrentDate = new Date(momentZone.parseZone(new Date().setDate(new Date().getDate() - 1)).local(true).toDate().toDateString());
              var Enddate = new Date(element.overdue_date);
              let dt = Enddate.getTime() - CurrentDate.getTime();
              let days = Math.floor(dt / (1000 * 60 * 60 * 24));
              if (days <= 0) {
                days = Math.abs(days);
                element.status = 'Overdue';
                element['OverDueShow'] = 'Overdue by ' + days + ' days';
              }
            }
          }
        } else {

          if (element.type == 'Events') {
            if (element.status == 'Comming Soon') {
              element['status'] = 'In Progress';
            } else {
              element['status'] = 'Upcoming';
            }
          }
        }
        if (new Date(element.due_date) > new Date())
          element['datelable'] = 'Due';
        else if (element.status == 'Completed')
          element['datelable'] = 'Completed';
        else element['datelable'] = 'Due';
      } else {
        element['DateStringcompleted_date'] = '';
        if (element.completed_date) {
          element['DateStringcompleted_date'] = new Date(
            element.completed_date
          ).toDateString();
        }
        element['datelable'] = 'Completed';
      }
      if (element.title_type == 'Section') {
        title_id = element.section_id;
      }
      element['title_id'] = title_id;
      if (window.sessionStorage.getItem('main_title_id') != null && window.sessionStorage.getItem('main_title_id') != undefined) {
        this.main_title_id = window.sessionStorage.getItem('main_title_id');
        sessionStorage.removeItem('main_title_id');
      }
    });
    this.listData = this.ScheduleList;
    await this.spinner.hide();
    if (new Date(this.exam_date) < new Date(this.ScheduleList[this.ScheduleList.length - 1].sortdate)) {
      this.ShowSuffienttime = true;
      this.SelfCheckBox = true;
      this.balance = 0;
      this.sprint = 0;
      this.insane = 0;
    } else {
      this.ShowSuffienttime = false;
      this.misMatchSchedule = false;
    }
  }
  async liveClassAfterApiCall(scheduleData: any) {
    this.sharedDataService.setScheduleData(scheduleData)
    this.calScheduleList = [];
    this.bkpScheduleList = [];
    this.ScheduleList = [];
    this.bkpSelfScheduleList = [];
    this.calScheduleList = scheduleData;
    this.LiveClassEventChange();
    this.GetCalTime();
    if (this.calScheduleList && this.calScheduleList.length > 0) {
      this.calScheduleList.sort(
        (a, b) =>
          new Date(a.due_date).getTime() -
          new Date(b.due_date).getTime() || a.cou - b.cou
      );
      this.calScheduleList.forEach((element, i) => {
        if (element.due_date) {
          if (i == 0)
            this.startdate = this.study_date != undefined
              ? new Date(this.study_date)
              : new Date(element.due_date);
          if (i == this.calScheduleList.length - 1)
            this.enddate = new Date(element.due_date);
          if (element.status != 'Completed') {
            var CurrentDate = momentZone.parseZone(new Date()).local(true).toDate();
            var startExamdate = new Date(element.due_date);
            var StartExam_Dt = startExamdate.getTime() - CurrentDate.getTime();
            var StartDateDay = Math.floor(StartExam_Dt / (1000 * 60 * 60 * 24)) + 1;
            if (StartDateDay <= 0) {
              element['DateStringvalue'] = '';
              if (element.createdAt) {
                element['DateStringvalue'] = new Date(element.createdAt).toDateString();
              }
              element['DateStringdue_date'] = '';
              if (element.due_date) {
                element['DateStringdue_date'] = new Date(element.due_date).toDateString();
              }
              element['DateStringoverdue_date'] = '';
              if (element.overdue_date) {
                element['DateStringoverdue_date'] = new Date(element.overdue_date).toDateString();
              }
              element['DateStringcompleted_date'] = '';
              if (element.completed_date) {
                element['DateStringcompleted_date'] = new Date(element.completed_date).toDateString();
              }
            } else {
              element['DateStringvalue'] = '';
              if (element.due_date) {
                element['DateStringvalue'] = new Date(
                  element.due_date
                ).toDateString();
              }
              element['DateStringdue_date'] = '';
              if (element.due_date) {
                element['DateStringdue_date'] = new Date(
                  element.due_date
                ).toDateString();
              }
              element['DateStringoverdue_date'] = '';
              if (element.overdue_date) {
                element['DateStringoverdue_date'] = new Date(
                  element.overdue_date
                ).toDateString();
              }
              element['DateStringcompleted_date'] = '';
              if (element.completed_date) {
                element['DateStringcompleted_date'] = new Date(
                  element.completed_date
                ).toDateString();
              }
            }
            if (new Date(element.due_date) > new Date())
              element['datelable'] = 'Available';
            else if (element.status == 'Completed')
              element['datelable'] = 'Completed';
            else element['datelable'] = 'Due';
            element['sortdate'] = element.due_date;
          } else {
            element['DateStringcompleted_date'] = '';
            if (element.completed_date) {
              element['DateStringcompleted_date'] = new Date(
                element.completed_date
              ).toDateString();
            }
            element['DateStringdue_date'] = '';
            if (element.due_date) {
              element['DateStringdue_date'] = new Date(element.due_date).toDateString();
            }
            element['datelable'] = 'Completed';
            element['sortdate'] = element['DateStringcompleted_date'];
          }
        }
      });
      var scheduldata = this.calScheduleList.filter((x) => x.due_date);
      var new_scheduldata = scheduldata.filter((x) => x.is_day_event !== false);
      this.ScheduleList = new_scheduldata;
      if (
        this.IsSelfSchedule &&
        this.IsSelfScheduleDay &&
        this.IsSelfPacedClass
      ) {
        let hrs = 0;
        let oldDate = '';
        this.ScheduleList.forEach((sch, i) => {
          if (sch.due_date) {
            if (i == 0)
              this.startdate =
                this.study_date != undefined
                  ? new Date(this.study_date)
                  : new Date(sch.due_date);
            if (i == this.calScheduleList.length - 1)
              this.enddate = new Date(sch.due_date);
          }
          if (i == 0 && this.IsSelfPacedClass) {
            if (
              sch.type != 'title' ||
              sch.title_type == 'Flashcard App' ||
              sch.title_type == 'Practice Question App'
            )
              this.bkpScheduleList.push(this.ReArrengeArray(sch));
          }
          if (sch.time && sch.type != 'Events') {
            if (oldDate == '') {
              oldDate =
                this.study_date != undefined
                  ? new Date(this.study_date).toDateString()
                  : new Date(sch.sortdate).toDateString();
            }
            this.GetchangeDate(oldDate);
            oldDate = this.GetDate;
            let day = new Date(oldDate).getDay();
            let noOfHrs =
              day == 0
                ? this.hsun
                : day == 1
                  ? this.hmon
                  : day == 2
                    ? this.htues
                    : day == 3
                      ? this.hwed
                      : day == 4
                        ? this.hthurs
                        : day == 5
                          ? this.hfri
                          : day == 6
                            ? this.hsat
                            : 0;
            if (sch.typeVid) {
              hrs =
                hrs +
                (parseInt(sch.time.split(':')[0]) / 60 +
                  sch.time.split(':')[1] / 60 / 60) *
                this.intervalTime;
            } else {
              hrs =
                hrs +
                (parseInt(sch.time.split(':')[0]) +
                  sch.time.split(':')[1] / 60) *
                this.intervalTime;
            }
            if (oldDate != new Date(oldDate).toDateString()) {
              hrs = 0;
            }
            if (hrs > noOfHrs && sch.type != 'title') {
              let oldNewDate = new Date(oldDate);
              if (new Date(oldNewDate) > new Date())
                sch['datelable'] = 'Available';
              else if (sch.status == 'Completed')
                sch['datelable'] = 'Completed';
              else sch['datelable'] = 'Due';
              let oldNewdata = {
                DateStringcompleted_date: sch.DateStringcompleted_date,
                DateStringdue_date: new Date(oldNewDate).toDateString(),
                DateStringoverdue_date: new Date(oldNewDate).toDateString(),
                DateStringvalue: new Date(oldNewDate).toDateString(),
                KA_access: sch.KA_access,
                cohort_id: sch.cohort_id,
                completed_date: sch.completed_date,
                createdAt: sch.createdAt,
                due_date: new Date(oldNewDate).toString(),
                due_number: sch.due_number,
                examname: sch.examname,
                id: sch.id,
                ketexam_name: sch.ketexam_name,
                knowass_name: sch.knowass_name,
                overdue_date: sch.overdue_date,
                overdue_number: sch.overdue_number,
                practice_name: sch.practice_name,
                required: sch.required,
                sortdate: new Date(oldNewDate).toString(),
                status: sch.status,
                time: sch.time,
                ttlcomplete: sch.ttlcomplete,
                ttlq: sch.ttlq,
                ttlqpending: sch.ttlq - sch.ttlcomplete,
                type: sch.type,
                type_id: sch.type_id,
                updatedAt: sch.updatedAt,
                typeVid: sch.typeVid,
                videolength: sch.videolength,
                percentage: sch.percentage,
                percentagecircle: sch.percentagecircle,
                datelable: sch.datelable,
                section_id: sch.section_id,
                ProgessPer: sch.ProgessPer,
                homework: sch.homework,
                event_url: sch.event_url,
                meeting_playform: sch.meeting_playform,
                title_type: sch.title_type,
                download_description: sch.download_description,
                download_url: sch.download_url,
                download_url_720p: sch.download_url_720p,
                download_url_480p: sch.download_url_480p,
                download_url_360p: sch.download_url_360p,
                download_url_240p: sch.download_url_240p,
                download_url_144p: sch.download_url_144p,
                alreadyJoin: sch.alreadyJoin,
              };
              this.bkpScheduleList.push(oldNewdata);

              this.changeDate = false;
              let newDate = new Date(oldDate).setDate(
                new Date(oldDate).getDate() + 1
              );
              this.GetchangeDate(new Date(newDate));
              newDate = this.GetDate;
              if (new Date(newDate) > new Date())
                sch['datelable'] = 'Available';
              else if (sch.status == 'Completed')
                sch['datelable'] = 'Completed';
              else sch['datelable'] = 'Due';
              this.ScheduleList.sort(
                (a, b) =>
                  new Date(a.due_date).getTime() -
                  new Date(b.due_date).getTime() || a.cou - b.cou
              );
              oldDate = new Date(newDate).toDateString();
              this.changeDate = false;
              if (sch.typeVid) {
                hrs =
                  parseInt(sch.time.split(':')[0]) / 60 +
                  sch.time.split(':')[1] / 60 / 60;
              } else {
                hrs =
                  parseInt(sch.time.split(':')[0]) +
                  sch.time.split(':')[1] / 60;
              }
            } else {
              let newDate = new Date(oldDate);
              if (new Date(newDate) > new Date())
                sch['datelable'] = 'Available';
              else if (sch.status == 'Completed')
                sch['datelable'] = 'Completed';
              else sch['datelable'] = 'Due';
              let olddata = {
                DateStringcompleted_date: sch.DateStringcompleted_date,
                DateStringdue_date: new Date(newDate).toDateString(),
                DateStringoverdue_date: new Date(
                  newDate
                ).toDateString(),
                DateStringvalue: new Date(newDate).toDateString(),
                KA_access: sch.KA_access,
                cohort_id: sch.cohort_id,
                completed_date: sch.completed_date,
                createdAt: sch.createdAt,
                due_date: new Date(newDate).toString(),
                due_number: sch.due_number,
                examname: sch.examname,
                id: sch.id,
                ketexam_name: sch.ketexam_name,
                knowass_name: sch.knowass_name,
                overdue_date: sch.overdue_date,
                overdue_number: sch.overdue_number,
                practice_name: sch.practice_name,
                required: sch.required,
                sortdate: new Date(newDate).toString(),
                status: sch.status,
                time: sch.time,
                ttlcomplete: sch.ttlcomplete,
                ttlq: sch.ttlq,
                ttlqpending: sch.ttlq - sch.ttlcomplete,
                type: sch.type,
                type_id: sch.type_id,
                updatedAt: sch.updatedAt,
                typeVid: sch.typeVid,
                videolength: sch.videolength,
                percentage: sch.percentage,
                percentagecircle: sch.percentagecircle,
                datelable: sch.datelable,
                section_id: sch.section_id,
                ProgessPer: sch.ProgessPer,
                homework: sch.homework,
                event_url: sch.event_url,
                meeting_playform: sch.meeting_playform,
                title_type: sch.title_type,
                download_description: sch.download_description,
                download_url: sch.download_url,
                download_url_720p: sch.download_url_720p,
                download_url_480p: sch.download_url_480p,
                download_url_360p: sch.download_url_360p,
                download_url_240p: sch.download_url_240p,
                download_url_144p: sch.download_url_144p,
                alreadyJoin: sch.alreadyJoin,
              };
              this.bkpScheduleList.push(olddata);
            }
          } else {
            this.bkpScheduleList.push(sch);
          }
          if (i == this.calScheduleList.length - 1)
            this.enddate = new Date(oldDate);
        });
        this.ScheduleList = this.bkpScheduleList;
      }
      this.ScheduleList.sort(
        (a, b) =>
          new Date(a.due_date).getTime() -
          new Date(b.due_date).getTime() || a.cou - b.cou
      );
    }
    let title_id = '';
    this.ScheduleList.forEach((element) => {
      if (element.status != 'Completed') {
        var CurrentDate = momentZone
          .parseZone(new Date())
          .local(true)
          .toDate();
        var startExamdate = new Date(element.due_date);
        var StartExam_Dt =
          startExamdate.getTime() - CurrentDate.getTime();
        var StartDateDay = Math.floor(StartExam_Dt / (1000 * 60 * 60 * 24)) + 1;
        if (StartDateDay <= 0) {
          if (element.status == 'Not Started' || element.status == 'In Progress') {
            if (element.overdue_date) {
              if (this.IsSelfPacedClass) {
                element.overdue_date = new Date(
                  new Date(element.due_date).setDate(
                    new Date(element.due_date).getDate() + 1
                  )
                );
              }
              var CurrentDate = new Date(momentZone.parseZone(new Date().setDate(new Date().getDate() - 1)).local(true).toDate().toDateString());
              var Enddate = new Date(element.overdue_date);
              let dt = Enddate.getTime() - CurrentDate.getTime();
              let days = Math.floor(dt / (1000 * 60 * 60 * 24));
              if (days <= 0) {
                days = Math.abs(days);
                element.status = 'Overdue';
                element['OverDueShow'] = 'Overdue by ' + days + ' days';
              }
            }
          }
        } else {
          if (!this.IsHybridClass) {
            if (element.status == 'Comming Soon') {
              element['status'] = 'In Progress';
            } else {
              element['status'] = 'Upcoming';
            }
          }
        }
        if (new Date(element.due_date) > new Date())
          element['datelable'] = 'Available';
        else if (element.status == 'Completed')
          element['datelable'] = 'Completed';
        else {
          element['datelable'] = 'Due';
        }
      } else {
        element['DateStringcompleted_date'] = '';
        if (element.completed_date) {
          element['DateStringcompleted_date'] = new Date(
            element.completed_date
          ).toDateString();
        }
        element['datelable'] = 'Completed';
      }
      if (element.title_type == 'Section') {
        title_id = element.section_id;
      }
      element['title_id'] = title_id;
      if (
        window.sessionStorage.getItem('main_title_id') != null &&
        window.sessionStorage.getItem('main_title_id') != undefined
      ) {
        this.main_title_id =
          window.sessionStorage.getItem('main_title_id');
        sessionStorage.removeItem('main_title_id');
      }
    });
    this.spinner.hide();
  }
  async scduledataall() {
    let scheduleSharedData = this.sharedDataService.getScheduleData()
    // if (scheduleSharedData && scheduleSharedData.length > 0) {
    //   if (this.IsSelfPacedClass) {
    //     this.selfPacedAfterApiCall(scheduleSharedData)
    //   } else {
    //     this.liveClassAfterApiCall(scheduleSharedData)
    //   }
    // } 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
          var userId = localStorage.getItem('CisspUserId');
        }
        var cer_id = localStorage.getItem('CisspCourseId');
        var cohort_id = localStorage.getItem('cohort_id');

        let method_id = localStorage.getItem('method');
        let method_type = localStorage.getItem('course_type');
        let material_type = 'Video';
        this.ScheduleList = [];
        if (this.IsSelfPacedClass) {
          await this.ScheduleserviceService.SelfschedulesData(
            token,
            method_id,
            method_type,
            userId,
            cohort_id
          ).then(async (data) => {
            if (data[0].status == 200) {
              this.spinner.hide();
              var list = JSON.parse(<string>data[0].json);
              this.selfPacedAfterApiCall(list.data)
            }
          });

        } else {
          await this.ScheduleserviceService.schedulesData(token, userId, cer_id, cohort_id, method_id, method_type, material_type).then(async (data) => {
            if (data[0].status == 200) {
              this.spinner.hide();
              var list = JSON.parse(<string>data[0].json);
              this.liveClassAfterApiCall(list.data)
            }
          });
        }
      });
      this.spinner.hide();
    // }
  }
  StartExam(item) {
    window.sessionStorage.setItem('main_title_id', item.title_id);
    if (item.type != 'VideoLesson' && item.type != 'MindMap') {
      this.sharedDataService.setScheduleData([])
      this.sharedDataService.setBaselineData([])
    }
    if (item.type == 'KA') {
      var data = {
        knowass_name: item.examname,
      };
      localStorage.setItem('CisspknowAssId', item.type_id);
      localStorage.setItem('CisspknowRowNumber', item.RowNumber ? item.RowNumber : 0);
      localStorage.setItem('KnowAssData', JSON.stringify(data));
      this.router.navigate([`/sidenav/knowledgeQue`]);
    } else if (item.type == 'CAT') {
      var datas = btoa(JSON.stringify(item.type_id));
      datas = encodeURIComponent(datas);
      this.router.navigate([`/cateexamtestque/${datas}`]);
    } else if (item.type == 'PRACTICE') {
      var itemdaa = {
        id: item.type_id,
        type: '',
      };
      var setdata = btoa(JSON.stringify(itemdaa));
      setdata = encodeURIComponent(setdata);
      this.router.navigate([`/practicetestque/${setdata}`]);
    } else if (item.type == 'VideoLesson') {
      if (item.title_type != 'Video' && item.title_type != 'video') {
        var type_id = {
          id: item.type_id,
        };
        this.VideoPopup = type_id;
      } else {
        this.VideoLink = item.download_url;
        this.selectedVideo = item;
        this.selectedPlaybackSpeed = "Normal";
        this.selectedVideoQuality = "1080p HD";
        this.videoQualityOptions = [];
        if (item.download_url) { this.videoQualityOptions.push('1080p HD') }
        if (item.download_url_720p) { this.videoQualityOptions.push('720p') }
        if (item.download_url_360p) { this.videoQualityOptions.push('480p') }
        if (item.download_url_480p) { this.videoQualityOptions.push('360p') }
        if (item.download_url_240p) { this.videoQualityOptions.push('240p') }
        if (item.download_url_144p) { this.videoQualityOptions.push('144p') }
        this.SelfPacedVideoPopupInfo = item
        this.SelfPacedVideoPopup = true;
      }
    } else if (item.type == 'MindMap') {
      var type_id = {
        id: item.type_id,
      };
      this.MindmapPopup = type_id;
    } else if (item.type == 'Events') {
      var eventinfo = btoa(JSON.stringify(item.type_id));
      this.router.navigate([`/eventrecordings/${eventinfo}`]);
    }
  }
  OnSelfPacedVideoComplate() {
    var userId = localStorage.getItem('CisspUserId');
    var cohort_id = localStorage.getItem('cohort_id');
    var SelfpacedUserData = {
      type_id: this.SelfPacedVideoPopupInfo.section_id,
      cohort_id: cohort_id,
      name: this.SelfPacedVideoPopupInfo.examname,
      user_id: userId,
      is_completed: 1
    }
    this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.router.navigate(['/login']);
      } else {
        var token = session
        this.ScheduleserviceService.SaveSelfpacedVideoData(
          SelfpacedUserData,
          token
        ).then(async (data) => {
          this.ScheduleList.forEach((element) => {
            if (element.section_id == this.SelfPacedVideoPopupInfo.section_id) {
              element['datelable'] = "Completed"
              element['status'] = "Completed"
              element['ProgessPer'] = 100
              this.sharedDataService.setScheduleData([])
            }
          })
        });
      }
    });
  }
  OverdueStartExam(item) {
    this.sharedDataService.setBaselineData([])
    this.sharedDataService.setScheduleData([])
    if (item.type == 'KA') {
      var data = {
        knowass_name: item.examname,
      };
      localStorage.setItem('CisspknowAssId', item.type_id);
      localStorage.setItem('CisspknowRowNumber', item.RowNumber ? item.RowNumber : 0);
      localStorage.setItem('KnowAssData', JSON.stringify(data));

      this.router.navigate([`/sidenav/knowledgeQue`]);
    } else if (item.type == 'CAT') {
      var datas = btoa(JSON.stringify(item.type_id));
      datas = encodeURIComponent(datas);
      this.router.navigate([`cateexamtestque/${datas}`]);
    } else if (item.type == 'PRACTICE') {
      var itemdaa = {
        id: item.type_id,
        type: '',
      };
      var setdata = btoa(JSON.stringify(itemdaa));
      setdata = encodeURIComponent(setdata);
      this.router.navigate([`practicetestque/${setdata}`]);
    }
  }
  async Viewresult(item) {
    if (item.type == 'KA' || item.type == 'KA_revision') {
      var KA_obj = this.calScheduleList.filter(obj => obj.type_id == item.type_id && obj.type == 'KA');
      if (KA_obj.length == 0) {
        KA_obj[0] = item
      }

      let correct = KA_obj[0].correct;
      let wrong = KA_obj[0].wrong;
      let dknow = item.ttlq - (correct + wrong);

      let correctPer = Math.round(correct * 100 / item.ttlq)
      let incorrectPer = Math.round(wrong * 100 / item.ttlq)
      let dknowPer = 100 - (correctPer + incorrectPer)

      var knowass_name = {
        knowass_name: item.examname,
      };
      debugger;
      var KA_info = {
        ass_id: item.type_id,
        correct: correct,
        wrong: wrong,
        dknow: dknow,
        currect_per: correctPer,
        incurrect_per: incorrectPer,
        dontknow_per: dknowPer,
        total: item.ttlq,
      }
      localStorage.setItem('CisspknowAssId', item.type_id);
      localStorage.setItem('KnowAssData', JSON.stringify(knowass_name));
      localStorage.setItem('CisspknowRowNumber', item.RowNumber ? item.RowNumber : 0);

      var data = btoa(JSON.stringify(KA_info));
      await this.router.navigate([`/sidenav/knowledgeresult/${data}`]);
    } else if (item.type == 'CAT') {
      var datas = btoa(JSON.stringify(item.type_id));
      datas = encodeURIComponent(datas);
      this.router.navigate([`/sidenav/cateexamtestresult/${datas}`]);
    } else if (item.type == 'PRACTICE' || item.type == 'Test_revision') {
      let incurrect_per = Math.round(100 - item.percentage);
      let currect = Math.round(item.percentage * item.ttlq / 100);
      let wrong = item.ttlq - currect;
      var dataPass = {
        test_id: item.type_id,
        RowNumber: 0,
        currect: currect,
        wrong: wrong,
        currect_per: item.percentage,
        incurrect_per: incurrect_per,
        total: item.ttlq,
      }
      var datapra = btoa(JSON.stringify(dataPass));
      datapra = encodeURIComponent(datapra);
      this.router.navigate([`sidenav/practicetestresult/${datapra}`]);
    }
  }
  ResumeTest(item) {
    this.sharedDataService.setScheduleData([])
    this.sharedDataService.setBaselineData([])
    if (item.type == 'KA') {
      var data = {
        knowass_name: item.examname,
      };
      localStorage.setItem('CisspknowAssId', item.type_id);
      localStorage.setItem('KnowAssData', JSON.stringify(data));
      localStorage.setItem('CisspknowRowNumber', item.RowNumber ? item.RowNumber : 0);
      this.router.navigate([`/sidenav/knowledgeQue`]);
    } else if (item.type == 'CAT') {
      var datas = btoa(JSON.stringify(item.type_id));
      datas = encodeURIComponent(datas);
      this.router.navigate([`cateexamtestque/${datas}`]);
    } else if (item.type == 'PRACTICE') {
      var itemdaa = {
        id: item.type_id,
        type: '',
      };
      var setdata = btoa(JSON.stringify(itemdaa));
      setdata = encodeURIComponent(setdata);
      this.router.navigate([`practicetestque/${setdata}`]);
    }
  }
  createWeekly() {
    var startdate = new Date(this.startdate),
      enddate = new Date(this.enddate);
    this.ScheduleList.forEach((element, i) => {
      if (i == 0) startdate = this.ScheduleList[i].due_date;
      if (i == this.ScheduleList.length - 1) {
        if (this.IsSelfPacedClass == false) {
          enddate = this.ScheduleList[i].due_date;
        } else {
          enddate = this.exam_date;
        }
      }
    });

    let CountMonth = this.monthDiff(new Date(startdate), new Date(enddate));
    let DateStart = new Date(startdate);
    for (let i = 0; i < CountMonth; i++) {
      let year = new Date(DateStart).getFullYear();
      let month = new Date(DateStart).getMonth();
      let total_week = this.weeksOfMonth(year, month);
      for (let i = 0; i < total_week; i++) {
        this.generateWeeklyView(this.getDateOfWeek(i + 1, month, year));
      }
      var now = new Date(DateStart);
      if (now.getMonth() == 11) {
        DateStart = new Date(now.getFullYear() + 1, 0, 1);
      } else {
        DateStart = new Date(now.getFullYear(), now.getMonth() + 1, 1);
      }
    }
    var main = [];
    var diff = (new Date(new Date(startdate).toDateString()).getTime() - new Date(new Date(enddate).toDateString()).getTime()) / 1000;
    diff /= 60 * 60 * 24 * 7;
    var diffweek = Math.abs(Math.round(diff));
    let DateSetStart = new Date(new Date(startdate).toDateString());
    DateSetStart = this.getDay(DateSetStart);
    for (let index = 0; index <= diffweek + 1; index++) {
      var mainsub = [];
      let weekday = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat'];
      for (let i = 0; i < 7; i++) {
        let data = {};
        var fulldate = weekday[i] + ' ' +
          this.months[DateSetStart.getMonth()] + ' ' +
          DateSetStart.getDate() + ' ' +
          DateSetStart.getFullYear().toString();
        var dateset = new Date(fulldate).toDateString();
        var currentDate = new Date(this.auth.ConvertDateDDFormat(new Date(), this.timezone, 'YYYY-MM-DD')).toDateString();
        var dataschedule = this.ScheduleList.filter((item) => item.DateStringdue_date == dateset && item.KA_access == 1);
        data = {
          fulldate: dateset,
          Date: DateSetStart.getDate(),
          Day: weekday[i],
          Month: this.months[DateSetStart.getMonth()],
          Year: DateSetStart.getFullYear().toString().substr(-2),
          CurrentDay: dateset == currentDate ? true : false,
          ScheduleData: dataschedule,
          dateset: new Date(fulldate).toDateString(),
        };
        mainsub.push(data);
        DateSetStart = new Date(new Date(new Date(DateSetStart).setDate(new Date(DateSetStart).getDate() + 1)).toDateString());
      }
      main.push(mainsub);
    }
    this.MainWeekData = main;
  }

  getDay(d) {
    d = new Date(d);
    var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -7 : 0);
    return new Date(d.setDate(diff));
  }
  weeksOfMonth(year, monthi) {
    const d = new Date(year, monthi + 1, 0);
    const adjustedDate = d.getDate() + d.getDay();
    return Math.ceil(adjustedDate / 7);
  }
  getDateOfWeek(w, m, y) {
    var d = 1 + (w - 1) * 7;
    return new Date(y, m, d);
  }
  generateWeeklyView(date) {
    let d = new Date(date);
    let t = d.getDay();
    let weekday = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat'];
    let totalDays = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
    this.WeekData = [];
    for (let i = 0, j = 1; i < weekday.length; i++) {
      let x = t - i;
      let data = {};
      if (t > i) {
        var fulldate =
          weekday[i] + ' ' +
          this.months[d.getMonth()] + ' ' +
          (d.getDate() - x) + ' ' +
          d.getFullYear().toString();
        var dateset = new Date(fulldate).toDateString();
        if (d.getDate() - x == 0) {
          data = {
            fulldate: '',
            Date: d.getDate() - x,
            Day: weekday[i],
            Month: this.months[d.getMonth()],
            Year: d.getFullYear().toString().substr(-2),
            CurrentDay: false,
            ScheduleData: [],
            dateset: new Date(fulldate).toDateString(),
          };
        } else {
          var dataschedule = [];
          var dataschedule = this.ScheduleList.filter(
            (item) =>
              (item.DateStringdue_date == dateset &&
                item.KA_access == 1 &&
                (item.status == 'Not Started' ||
                  item.status == 'In Progress')) ||
              (item.DateStringoverdue_date == dateset &&
                item.KA_access == 1 &&
                item.status == 'Overdue') ||
              (item.DateStringcompleted_date == dateset &&
                item.KA_access == 1 &&
                item.status == 'Completed') ||
              (item.DateStringvalue == dateset &&
                item.KA_access == 1 &&
                item.status == 'Upcoming')
          );
          data = {
            fulldate: '',
            Date: d.getDate() - x,
            Day: weekday[i],
            Month: this.months[d.getMonth()],
            Year: d.getFullYear().toString().substr(-2),
            CurrentDay: false,
            ScheduleData: dataschedule,
            dateset: new Date(fulldate).toDateString(),
          };
        }
      } else if (t < i) {
        var fulldate =
          weekday[i] + ' ' +
          this.months[d.getMonth()] + ' ' +
          (d.getDate() + j) + ' ' +
          d.getFullYear().toString();
        var dateset = new Date(fulldate).toDateString();
        var dataschedule = this.ScheduleList.filter(
          (item) =>
            (item.DateStringdue_date == dateset &&
              item.KA_access == 1 &&
              (item.status == 'Not Started' || item.status == 'In Progress')) ||
            (item.DateStringoverdue_date == dateset &&
              item.KA_access == 1 &&
              item.status == 'Overdue') ||
            (item.DateStringcompleted_date == dateset &&
              item.KA_access == 1 &&
              item.status == 'Completed') ||
            (item.DateStringvalue == dateset &&
              item.KA_access == 1 &&
              item.status == 'Upcoming')
        );
        data = {
          fulldate: dateset,
          Date: d.getDate() + j,
          Day: weekday[i],
          Month: this.months[d.getMonth()],
          Year: d.getFullYear().toString().substr(-2),
          CurrentDay: false,
          ScheduleData: dataschedule,
          dateset: new Date(fulldate).toDateString(),
        };
        j++;
      } else if (t === i) {
        var fulldate =
          weekday[i] + ' ' +
          this.months[d.getMonth()] + ' ' +
          d.getDate() + ' ' +
          d.getFullYear().toString();
        var dateset = new Date(fulldate).toDateString();
        var dataschedule = this.ScheduleList.filter(
          (item) =>
            (item.DateStringdue_date == dateset &&
              item.KA_access == 1 &&
              (item.status == 'Not Started' || item.status == 'In Progress')) ||
            (item.DateStringoverdue_date == dateset &&
              item.KA_access == 1 &&
              item.status == 'Overdue') ||
            (item.DateStringcompleted_date == dateset &&
              item.KA_access == 1 &&
              item.status == 'Completed') ||
            (item.DateStringvalue == dateset &&
              item.KA_access == 1 &&
              item.status == 'Upcoming')
        );
        data = {
          fulldate: dateset,
          Date: d.getDate(),
          Day: weekday[i],
          Month: this.months[d.getMonth()],
          Year: d.getFullYear().toString().substr(-2),
          CurrentDay: false,
          ScheduleData: dataschedule,
          dateset: new Date(fulldate).toDateString(),
        };
      }
      if (parseInt(data['Date']) <= totalDays) this.WeekData.push(data);
    }
    this.MainWeekData.push(this.WeekData);
  }
  getOrdinal(n) {
    if (n == 31) {
      return n + 'st';
    } else {
      let ord = [, 'st', 'nd', 'rd'];
      let exceptions = [11, 12, 13];
      let nth = ord[n % 100] == undefined || exceptions.includes(n % 100)
        ? 'th'
        : ord[n % 100];
      return n + nth;
    }
  }
  Nextmonth() {
    this.selected_schedule = {};
    this.isShowSchedule = false;
    this.activestatus = 'Next Month';
    this.startdate.setMonth(this.startdate.getMonth() + 1);
    this.startdate = new Date(this.startdate);
    this.datesort();
  }
  previous() {
    this.selected_schedule = {};
    this.isShowSchedule = false;
    this.activestatus = 'Previous Month';
    this.startdate.setMonth(this.startdate.getMonth() - 1);
    this.startdate = new Date(this.startdate);
    this.datesort();
  }
  Currentmonth() {
    this.selected_schedule = {};
    this.isShowSchedule = false;
    this.activestatus = 'Current Month';
    this.startdate = momentZone.parseZone(new Date()).local(true).toDate();
    this.datesort();
  }
  retuey() {
    window.location.reload();
  }
  GetchangeDate(getDateSet) {
    let day = new Date(getDateSet).getDay();
    let noHrs = 0;
    for (let i = 0; i < 7; i++) {
      noHrs =
        day == 0
          ? this.hsun
          : day == 1
            ? this.hmon
            : day == 2
              ? this.htues
              : day == 3
                ? this.hwed
                : day == 4
                  ? this.hthurs
                  : day == 5
                    ? this.hfri
                    : day == 6
                      ? this.hsat
                      : 0;
      if (noHrs != 0) {
        i = 6;
        this.changeDate = true;
      } else {
        if (noHrs == 0) this.changeDate = false;
        if (!this.changeDate) {
          getDateSet = new Date(
            new Date(getDateSet).setDate(new Date(getDateSet).getDate() + 1)
          ).toDateString();
        }
        day = new Date(getDateSet).getDay();
      }
    }
    this.GetDate = getDateSet;
  }
  monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 1 : months + 1;
  }
  GetCalTime() {
    this.noOfMin = 0;
    let cou = 0;
    if (this.calScheduleList && this.calScheduleList.length > 0) {
      if (!this.IsSelfPacedClass) {
        this.calScheduleList.sort(
          (a, b) =>
            momentZone
              .parseZone(a.completed_date ? a.completed_date : a.due_date)
              .local(true)
              .toDate()
              .getTime() -
            momentZone
              .parseZone(b.completed_date ? b.completed_date : b.due_date)
              .local(true)
              .toDate()
              .getTime()
        );
      }
      this.calScheduleList.forEach((cal, i) => {
        if (cal.type != 'Events') {
          cal.completed_date =
            cal.completed_date != '' && cal.completed_date != null
              ? momentZone
                .parseZone(new Date(cal.completed_date))
                .local(true)
                .toDate()
                .toString()
              : '';
          cal.createdAt =
            cal.createdAt != '' && cal.createdAt != ''
              ? momentZone
                .parseZone(new Date(cal.createdAt))
                .local(true)
                .toDate()
                .toString()
              : '';
          cal.due_date =
            cal.due_date != '' && cal.due_date != ''
              ? momentZone
                .parseZone(new Date(cal.due_date))
                .local(true)
                .toDate()
                .toString()
              : '';
          cal.overdue_date =
            cal.overdue_date != '' && cal.overdue_date != ''
              ? momentZone
                .parseZone(new Date(cal.overdue_date))
                .local(true)
                .toDate()
                .toString()
              : '';
          cal.updatedAt =
            cal.updatedAt != '' && cal.updatedAt != ''
              ? momentZone
                .parseZone(new Date(cal.updatedAt))
                .local(true)
                .toDate()
                .toString()
              : '';
        }
        if (cal.due_date) {
          if (i == 0) {
            this.startdate =
              this.study_date != undefined
                ? new Date(this.study_date)
                : new Date(cal.due_date);
          }
          if (i == this.calScheduleList.length - 1)
            this.enddate = new Date(cal.due_date);
          if (cal.status != 'Completed') {
            cal['sortdate'] = cal.due_date;
          } else {
            cal['DateStringcompleted_date'] = '';
            if (cal.completed_date) {
              cal['DateStringcompleted_date'] = new Date(
                cal.completed_date
              ).toDateString();
            }
            cal['sortdate'] = cal['DateStringcompleted_date'];
          }
          if (cal.Materials) {
            if (cal.Materials.VideoLesson) {
              cal.Materials.VideoLesson.forEach((element, i) => {
                cou += 1;
                element.view_date =
                  element.view_date != ''
                    ? momentZone
                      .parseZone(new Date(element.view_date))
                      .local(true)
                      .toDate()
                      .toString()
                    : '';
                let addVideoLessonData = {
                  DateStringcompleted_date: element.view_date,
                  DateStringdue_date: '',
                  DateStringoverdue_date: '',
                  DateStringvalue: '',
                  KA_access: cal.KA_access,
                  cohort_id: cal.cohort_id,
                  completed_date: element.view_date,
                  createdAt: cal.createdAt,
                  due_date: cal.due_date,
                  due_number: cal.due_number,
                  examname: element.video_title,
                  id: cal.id,
                  ketexam_name: cal.type == 'CAT' ? element.video_title : null,
                  knowass_name: cal.type == 'KA' ? element.video_title : null,
                  overdue_date: cal.overdue_date,
                  overdue_number: cal.overdue_number,
                  practice_name:
                    cal.type == 'PRACTICE' ? element.video_title : null,
                  required: cal.required,
                  sortdate: cal.sortdate,
                  status: element.status,
                  time: element.duration,
                  ttlcomplete: cal.ttlcomplete,
                  ttlq: 1,
                  ttlqpending: cal.ttlq - 1,
                  type: 'VideoLesson',
                  type_id: element.id,
                  updatedAt: cal.updatedAt,
                  cou: cou,
                  typeVid: 1,
                  videolength:
                    element.duration.split(':')[0] +
                    'm : ' +
                    element.duration.split(':')[1] +
                    's',
                  percentage: element['view_percent'],
                  homework: 0,
                };
                this.calScheduleList.push(addVideoLessonData);
              });
              if (cal.Materials.MindMap) {
                cal.Materials.MindMap.forEach((element, i) => {
                  cou += 1;
                  element.view_date =
                    element.view_date != ''
                      ? momentZone.parseZone(new Date(element.view_date)).local(true).toDate().toString()
                      : '';
                  let addMindMapLessonData = {
                    DateStringcompleted_date: element.view_date,
                    DateStringdue_date: '',
                    DateStringoverdue_date: '',
                    DateStringvalue: '',
                    KA_access: cal.KA_access,
                    cohort_id: cal.cohort_id,
                    completed_date: element.completed_date,
                    createdAt: cal.createdAt,
                    due_date: cal.due_date,
                    due_number: cal.due_number,
                    examname: element.name,
                    id: cal.id,
                    ketexam_name: cal.type == 'CAT' ? element.name : null,
                    knowass_name: cal.type == 'KA' ? element.name : null,
                    overdue_date: cal.overdue_date,
                    overdue_number: cal.overdue_number,
                    practice_name: cal.type == 'PRACTICE' ? element.name : null,
                    required: cal.required,
                    sortdate: cal.sortdate,
                    status: element.status,
                    time: element.duration,
                    ttlcomplete: cal.ttlcomplete,
                    ttlq: 1,
                    ttlqpending: cal.ttlq - 1,
                    type: 'MindMap',
                    type_id: element.id,
                    updatedAt: cal.updatedAt,
                    cou: cou,
                    typeVid: 1,
                    videolength: element.duration.split(':')[0] + 'm : ' +
                      element.duration.split(':')[1] + 's',
                    percentage: element['view_percent'],
                    homework: 0,
                  };
                  this.calScheduleList.push(addMindMapLessonData);
                });
              }
            }
          }
          if (cal.type == 'CAT' || cal.type == 'KA' || cal.type == 'PRACTICE') {
            cal['ProgessPer'] = (cal.ttlcomplete * 100) / cal.ttlq;
            cal['ProgessPer'] = cal['ProgessPer'] ? cal['ProgessPer'] : 0;
            cal['percentage'] = Math.round((100 * cal['correct']) / (cal['correct'] + cal['wrong']));
            cal['percentagecircle'] = cal['percentage'] + ' ' + (100 - cal['percentage']);
          }
          if (cal.type == 'VideoLesson' || cal.type == 'MindMap') {
            cal['ProgessPer'] = cal['percentage'];
            cal['percentage'] = cal['percentage'];
            cal['percentagecircle'] = cal['percentage'] + ' ' + (100 - cal['percentage']);
          }
          if (!this.IsSelfPacedClass) {
            cal['ttlqpending'] = cal.ttlq - cal.ttlcomplete;
            cou += 1;
            cal['cou'] = cou + 1;
            if (cal.type == 'KA' || cal.type == 'CAT' || cal.type == 'PRACTICE' || cal.type == 'title') {
              cal['typeVid'] = 0;
              cal['videolength'] = '';
            } else {
              if (!cal.Materials) {
                cal['KA_access'] = 1;
                cal['typeVid'] = 1;
                cal['videolength'] =
                  cal.time.split(':')[0] +
                  'm : ' +
                  cal.time.split(':')[1] +
                  's';
              }
            }
          }
        }
        if ((cal.ttlq == 0 || cal.ttlq == null) && (cal.type == 'KA' || cal.type == 'CAT' || cal.type == 'PRACTICE')) {
          cal.time = '00:00';
        }
        if (cal.time == null || cal.time == 0) {
          if (cal.type == 'KA') {
            if (cal.ttlq) {
              let d = parseInt(cal.ttlq) * (this.calKATime + this.know_ass_revision);
              var h = Math.floor(d / 3600) + '';
              var m = Math.floor((d % 3600) / 60) + '';
              h = h.toString().length == 1 ? '0' + h : h;
              m = m.toString().length == 1 ? '0' + m : m;
              cal.time = h + ':' + m;
            }
          } else if (cal.type == 'CAT') {
            if (cal.ttlq) {
              let d = parseInt(cal.ttlq) * this.calCatTime;
              var h = Math.floor(d / 3600) + '';
              var m = Math.floor((d % 3600) / 60) + '';
              h = h.toString().length == 1 ? '0' + h : h;
              m = m.toString().length == 1 ? '0' + m : m;
              cal.time = h + ':' + m;
            }
          } else if (cal.type == 'PRACTICE') {
            if (cal.ttlq) {
              let d =
                parseInt(cal.ttlq) *
                (this.calPracticeTime + this.practice_test_revision);
              var h = Math.floor(d / 3600) + '';
              var m = Math.floor((d % 3600) / 60) + '';
              h = h.toString().length == 1 ? '0' + h : h;
              m = m.toString().length == 1 ? '0' + m : m;
              cal.time = h + ':' + m;
            }
          } else if (cal.type == 'VideoLesson') {
            if (cal.duration) {
              cal.time = cal.duration;
            }
          } else if (cal.type == 'MindMap') {
            if (cal.duration) {
              cal.time = cal.duration;
            }
          } else {
            if (cal.ttlq) {
              let d = parseInt(cal.ttlq) * this.CalOtherTime;
              var h = Math.floor(d / 3600) + '';
              var m = Math.floor((d % 3600) / 60) + '';
              h = h.toString().length == 1 ? '0' + h : h;
              m = m.toString().length == 1 ? '0' + m : m;
              cal.time = h + ':' + m;
            } else {
              cal.time = '00:00';
            }
          }
        }
        if (cal.type == 'KA' || cal.type == 'CAT' || cal.type == 'PRACTICE') {
          this.noOfMin =
            this.noOfMin +
            parseInt(cal.time.split(':')[0]) * 60 +
            parseInt(cal.time.split(':')[1]);
        } else if (cal.title_type == 'Flashcard App') {
          this.noOfMin =
            this.noOfMin +
            parseInt(cal.time.split(':')[0]) * 60 +
            parseInt(cal.time.split(':')[1]);
        } 
        else if (cal.title_type == 'Practice Question App') {
          this.noOfMin =
            this.noOfMin +
            parseInt(cal.time.split(':')[0]) * 60 +
            parseInt(cal.time.split(':')[1]);
        } else {
          if (!cal.Materials){
            if (cal.time == null) {
                this.noOfMin = this.noOfMin + 0; 
            } else {
                this.noOfMin = this.noOfMin + parseInt(cal.time.split(':')[0]) + cal.time.split(':')[1] / 60;
            }
          }
        }
        if (cal.Materials) {
          if (cal.Materials.VideoLesson) {
            cal.Materials.VideoLesson.forEach((element) => {
              this.noOfMin =
                this.noOfMin +
                parseInt(element.duration.split(':')[0]) +
                element.duration.split(':')[1] / 60;
            });
          }
          if (cal.Materials.MindMap) {
            cal.Materials.MindMap.forEach((element) => {
              this.noOfMin =
                this.noOfMin +
                parseInt(element.duration.split(':')[0]) +
                element.duration.split(':')[1] / 60;
            });
          }
        }
      });
    }
    this.calScheduleList.sort((a, b) =>
      new Date(a.due_date).getTime() - new Date(b.due_date).getTime() || a.cou - b.cou
    );
    this.GetExamCalTime();
    this.calScheduleList.forEach((cal, i) => {
      if (cal.type == 'Events') {
        cal['completed_date'] =
          cal.complete_date != null || cal.completed_date != ''
            ? cal.complete_date
            : cal.overdue_date;
        cal['homework'] = 0;
        cal['event_minutes'] = cal['event_duration'];
        cal['event_duration'] =
          Math.floor(cal['event_duration'] / 60) == 0
            ? cal['event_duration'] + ' minutes'
            : Math.floor(cal['event_duration'] / 60) + ' hours';
        cal['meeting_playform'] = cal.meeting_playform;
      }
    });
  }
  async getAllComponentTime() {
    let lineData = this.sharedDataService.getComponentTimeData()
    if (lineData && lineData.length > 0) {
      this.flashcard_app = lineData[0].flashcard_app;
      this.flashcard_app_revision = lineData[0].flashcard_app_revision;
      this.practice_que_app = lineData[0].practice_que_app;
      this.practice_que_app_revision =
        lineData[0].practice_que_app_revision;
      this.know_ass_revision = lineData[0].know_ass_revision;
      this.practice_test_revision = lineData[0].practice_test_revision;
    } else {
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = session
          await this.ScheduleserviceService.getAllComponentTime(token).then(
            async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.sharedDataService.setComponentTimeData(list.data)
                this.flashcard_app = list.data[0].flashcard_app;
                this.flashcard_app_revision = list.data[0].flashcard_app_revision;
                this.practice_que_app = list.data[0].practice_que_app;
                this.practice_que_app_revision =
                  list.data[0].practice_que_app_revision;
                this.know_ass_revision = list.data[0].know_ass_revision;
                this.practice_test_revision = list.data[0].practice_test_revision;
              }
            }
          );
        }
      });
    }
  }

  GetExamCalTime() {
    this.intervalTime = 0;
    let diffTime = Math.abs(
      Date.parse(new Date(this.exam_date).toDateString()) -
      Date.parse(this.startdate.toDateString())
    );
    let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    let diffsechuleMonth =
      this.monthDiff(new Date(this.startdate), new Date(this.exam_date)) - 1;
    if (
      this.IsSelfSchedule &&
      this.IsSelfScheduleDay &&
      this.IsSelfPacedClass
    ) {
      let getDateSet = new Date(this.startdate).toDateString();
      let day = new Date(getDateSet).getDay();
      let noHrs = 0;
      let CountHrs = 0;
      for (let i = 0; i < diffDays; i++) {
        noHrs =
          day == 0
            ? this.hsun
            : day == 1
              ? this.hmon
              : day == 2
                ? this.htues
                : day == 3
                  ? this.hwed
                  : day == 4
                    ? this.hthurs
                    : day == 5
                      ? this.hfri
                      : day == 6
                        ? this.hsat
                        : 0;
        if (noHrs != 0) {
          CountHrs = CountHrs + noHrs;
        }
        getDateSet = new Date(
          new Date(getDateSet).setDate(new Date(getDateSet).getDate() + 1)
        ).toDateString();
        day = new Date(getDateSet).getDay();
      }

      this.SelfScheduleTime = CountHrs * 60;
    } else {
      this.SelfScheduleTime = this.isNotSelfSchedualTime * diffDays;
    }
    this.ErrorSelfSchedule = this.noOfMin;
    if (this.intervalTime == 0) {
      this.intervalTime = 1;
    }
  }
  SelfScheduleArray() {
    this.bkpSelfScheduleList = [];
    let cou = 1;
    this.calScheduleList.forEach((element) => {
      var title = '';
      var duration = '',
        type = '';
      if (element.material_type == 'Mindmap') {
        title = element.mindmap_title;
        duration = element.mindmap_duration;
        type = 'MindMap';
        element['typeVid'] = 1;
      } else if (element.material_type == 'Video') {
        title = element.video_title;
        duration = element.duration;
        type = 'VideoLesson';
        element['typeVid'] = 1;
      } else if (element.material_type == 'KA') {
        title = element.knowass_name;
        duration = null;
        type = 'KA';
        element['typeVid'] = 0;
      } else if (element.material_type == 'Test') {
        title = element.practice_name;
        duration = null;
        type = 'PRACTICE';
        element['typeVid'] = 0;
      } else if (element.material_type == 'CAT') {
        title = element.ketexam_name;
        duration = null;
        type = 'CAT';
        element['typeVid'] = 0;
      } else if (element.material_type == 'title') {
        title = element.title_name;
        duration = null;
        type = 'title';
        element['typeVid'] = 0;
      } else if (element.material_type == 'Events') {
        title = element.examname;
        duration = null;
        type = 'Events';
        element['typeVid'] = 0;
      }
      element.view_date =
        element.view_date != '' && element.view_date != null
          ? momentZone.parseZone(new Date(element.view_date)).local(true).toDate().toString()
          : '';
      if (element.material_type != 'Events') {
        element.due_date =
          element.due_date != '' && element.due_date != null
            ? momentZone.parseZone(new Date(element.due_date)).local(true).toDate().toString()
            : '';
        element['completed_date'] = element.view_date
          ? element.view_date
          : element.completed_date;
        element['status'] = element.status;
      } else {
        let timeZone = element.due_date.substr(element.due_date.length - 6, 6);
        let due_date: Date;
        let overdue_date;
        let currTimeZone = this.auth.currentTimeZone();
        if (currTimeZone.timeValue != timeZone) {
          due_date = new Date(element.due_date);
          overdue_date =
            due_date.getFullYear() + '-' +
            (due_date.getMonth() + 1).toString().padStart(2, '0') + '-' +
            due_date.getDate().toString().padStart(2, '0') + 'T' +
            element.end_time + ':00' +
            JSON.parse(element.event_time_zone).timeValue;
          overdue_date = new Date(overdue_date);
        } else {
          due_date = new Date(
            new Date(element.due_date).toLocaleString('en-US', {
              timeZone: this.timezone,
            })
          );
          overdue_date =
            due_date.getFullYear() + '-' +
            (due_date.getMonth() + 1).toString().padStart(2, '0') + '-' +
            due_date.getDate().toString().padStart(2, '0') + 'T' +
            element.end_time + ':00' +
            JSON.parse(element.event_time_zone).timeValue;
          overdue_date = new Date(
            new Date(overdue_date).toLocaleString('en-US', {
              timeZone: this.timezone,
            })
          );
        }
        let curr_date = new Date(
          new Date().toLocaleString('en-US', { timeZone: this.timezone })
        );
        let event_minutes = element.event_duration;
        let meet_url = '#';
        element.alreadyJoin = 0;
        if (new Date(due_date) > curr_date && element.is_completed != 1) {
          if (
            new Date(
              new Date(due_date).setMinutes(
                new Date(due_date).getMinutes() - 15
              )
            ) < curr_date
          ) {
            element.status = 'Comming Soon';
            if (element.meeting_playform == 2) {
              var eventstart = {
                id: element.id,
                title: element.examname,
                user_id: localStorage.getItem('CisspUserId'),
              };
              meet_url = environment.SITE_URL + '/startconference/' + encodeURIComponent(btoa(JSON.stringify(eventstart)));
            }
            if (element.meeting_playform == 1) {
              meet_url = element.event_url;
            }
          } else {
            element.status = 'Not Started';
          }
        } else if (
          element.is_completed == 1 ||
          (element.meeting_playform == 1 && new Date(overdue_date) < curr_date)
        ) {
          element.status = 'Completed';
          element.complete_date =
            element.meeting_playform == 2
              ? element.complete_date
              : new Date(
                this.auth.ConvertAnyTimeZoneToCurrentZone(
                  this.auth.ConvertFormatDbDateTime(
                    overdue_date,
                    this.timezone
                  ),
                  this.timezone
                )
              );
          element.completed_date =
            element.meeting_playform == 2
              ? element.complete_date
              : new Date(
                this.auth.ConvertAnyTimeZoneToCurrentZone(
                  this.auth.ConvertFormatDbDateTime(
                    overdue_date,
                    this.timezone
                  ),
                  this.timezone
                )
              );
        } else if (
          element.is_live == 1 ||
          (element.meeting_playform == 1 && new Date(due_date) < curr_date)
        ) {
          if (element.event_url && element.meeting_playform == 2) {
            meet_url = environment.SITE_URL + '/conference/' + encodeURIComponent(btoa(JSON.stringify(element.event_url)));
            element.status = 'In Progress';
            element.alreadyJoin = element.alreadyJoin;
          }
          if (element.event_url && element.meeting_playform == 1) {
            meet_url = element.event_url;
            element.status = 'In Progress';
            element.alreadyJoin = 0;
          }
        } else {
          element.status = 'Not Started';
        }
        element.event_time = this.auth.convertAnyTime12Hour(
          new Date(due_date).getHours() + ':' + new Date(due_date).getMinutes()
        );
        element.event_url = meet_url;
        element.event_duration = event_minutes;
        element.due_date = new Date(due_date);
      }

      if (element.status != 'Completed') {
        element['sortdate'] = element.due_date;
      } else {
        element['sortdate'] =
          element['completed_date'] == ''
            ? element['overdue_date']
            : element['completed_date'];
      }

      element['DateStringcompleted_date'] = element.view_date;
      element['DateStringdue_date'] = '';
      element['DateStringoverdue_date'] = '';
      element['DateStringvalue'] = '';
      element['KA_access'] = 1;
      element['cohort_id'] = element.cohort_id;
      element['createdAt'] = element.createdAt;
      element['due_date'] = element.due_date;
      element['due_number'] = 0;
      element['examname'] = title;
      element['section_id'] = element.id;
      element['id'] = element.material_id;
      element['ketexam_name'] = title;
      element['knowass_name'] = title;
      element['overdue_date'] = new Date(element['sortdate']).toDateString();
      element['overdue_number'] = 0;
      element['practice_name'] = title;
      element['required'] = element.required;
      element['sortdate'] = element.sortdate;
      element['time'] = duration;
      element['ttlcomplete'] = element.ttlcomplete;
      element['ttlq'] = element.ttlq;
      element['ttlqpending'] = element.ttlq - element.ttlcomplete;
      element['type'] = type;
      element['type_id'] = element.id;
      element['updatedAt'] = element.updatedAt;
      element['percentage'] = element['view_percent'];
      element['cou'] = cou;
      element['homework'] = 0;
      element['event_url'] = element.event_url;
      element['title_type'] = element.title_type;
      element['download_description'] = element.download_description;
      element['download_url'] = element.download_url;
      element['videolength'] =
        duration != null
          ? duration.split(':')[0] + 'm : ' + duration.split(':')[1] + 's'
          : duration;
      cou += 1;
    });
  }
  tabClick(item) {
    if (this.main_title_id == item.title_id) {
      this.main_title_id = '';
    } else {
      this.main_title_id = item.title_id;
    }
  }

  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 userid = parseInt(localStorage.getItem('CisspUserId'));
            if (item.type == 'KA') {
              await this.KnowledgeserviceService.getResetDataUser(
                userid,
                cohort_id,
                item.type_id,
                token
              ).then(async (data) => {
                if (data[0].status == 200) {
                  this.NoPrevRecordFound = false;
                  item.ViewSummery = true;
                  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.ttlq
                      );
                      element['knowass_name'] = item.knowass_name
                      element['type'] = 'KA';
                    });
                  } else {
                    this.NoPrevRecordFound = true;
                    item.ViewSummery = false;
                  }
                  this.KnowledgeName = item.knowass_name;
                  this.resetDatalist = list.data;
                  if (!this.Summery) {
                    this.ViewHistory = true;
                  } else {
                    this.ViewHistory = false;
                  }
                } else {
                  if (data[0].status == 0) {
                    this.newerror = true;
                  } else { }
                }

                await this.spinner.hide();
              });
            }
            if (item.type == 'PRACTICE') {
              await this.PracticeserviceService.getResetDataUser(
                userid,
                cohort_id,
                item.type_id,
                token
              ).then(async (data) => {
                if (data[0].status == 200) {
                  this.NoPrevRecordFound = false;
                  item.ViewSummery = true;
                  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.ttlq
                      );
                      element['type'] = 'PRACTICE';
                      element['ttlq'] = item.ttlq;
                    });
                  } else {
                    this.NoPrevRecordFound = true;
                    item.ViewSummery = false;
                  }
                  this.KnowledgeName = item.practice_name;
                  this.resetDatalist = list.data;

                  if (!this.Summery) {
                    this.ViewHistory = true;
                  } else {
                    this.ViewHistory = false;
                  }
                } else {
                  if (data[0].status == 0) {
                    this.newerror = true;
                  } else { }
                }

                await this.spinner.hide();
              });
            }
          }
        });
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }
  }

  async GotoResult(item) {
    if (item.type == 'KA') {
      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 KA_info = {
        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(KA_info));
      await this.router.navigate([`/sidenav/knowledgeresult/${data}`]);
    }
    if (item.type == 'PRACTICE') {
      let incurrect_per = Math.round(100 - item.percentage);
      let currect = Math.round(item.percentage * item.ttlq / 100);
      let wrong = item.ttlq - 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.ttlq,
      }
      var data = btoa(JSON.stringify(dataPass));
      data = encodeURIComponent(data);
      this.router.navigate([`sidenav/practicetestresult/${data}`]);
    }
  }
  showReset(item) {
    this.ResetNamedata = item;
    this.resetResult = true;
  }
  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');
        var userid = parseInt(localStorage.getItem('CisspUserId'));
        if (this.ResetNamedata.type == 'KA') {
          await this.KnowledgeserviceService.ResetKnow(
            this.ResetNamedata.type_id,
            userid,
            token,
            cohort_id
          ).then(
            async (data) => {
              if (data[0].status == 200) {
                await this.service.ShowSuccess(
                  this.ResetNamedata.knowass_name + ' reset successfully'
                );
                this.sharedDataService.setScheduleData([])
                this.sharedDataService.setKnowledgeAssessmentData([])
                await this.scduledataall();
                await this.spinner.hide();
              } else {
                await this.spinner.hide();
              }
            },
            (err) => {
              this.spinner.hide();
            }
          );
        }
        if (this.ResetNamedata.type == 'PRACTICE') {
          await this.PracticeserviceService.ResetTest(
            userid,
            this.ResetNamedata.type_id,
            token,
            cohort_id
          ).then(
            async (data) => {
              if (data[0].status == 200) {
                await this.service.ShowSuccess(
                  this.ResetNamedata.practice_name + ' reset successfully'
                );
                await this.scduledataall();
                await this.spinner.hide();
              } else {
                await this.spinner.hide();
              }
            },
            (err) => {
              this.spinner.hide();
            }
          );
        }
      }
    });
  }
  async HideSchedule() {
    this.UpdateSchedule = false;
    this.SelfCheckBox = false;
    this.ShowSuffienttime = false;
    this.ShowInvalidDate = false;
    this.misMatchSchedule = false;
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        var userId = localStorage.getItem('CisspUserId');
        var cer_id = localStorage.getItem('CisspCourseId');
        var cohort_id = localStorage.getItem('cohort_id');
        await this.ScheduleserviceService.getSelfSchedule(
          userId,
          cer_id,
          cohort_id,
          token
        ).then((data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            if (list.data.length > 0 && this.IsSelfPacedClass) {
              this.CustomeTitle = 'Create your own custom schedule';
              this.IsSelfSchedule = true;
              let vals = list.data[list.data.length - 1];
              this.self_schedule_id = vals.id;
              this.sun = vals.sun;
              this.mon = vals.mon;
              this.tues = vals.tues;
              this.wed = vals.wed;
              this.thurs = vals.thurs;
              this.fri = vals.fri;
              this.sat = vals.sat;
              this.hsun = vals.hsun;
              this.hmon = vals.hmon;
              this.htues = vals.htues;
              this.hwed = vals.hwed;
              this.hthurs = vals.hthurs;
              this.hfri = vals.hfri;
              this.hsat = vals.hsat;
              this.balance = vals.btn_balance;
              this.sprint = vals.btn_sprint;
              this.insane = vals.btn_insane;
              this.exam_date = vals.exam_date ? vals.exam_date : '';
              this.study_date = vals.study_date
                ? new Date(vals.study_date)
                : undefined;
            }
          }
        });
      }
    });
    this.disablePresetOption();
  }

  async GetOldHours() {
    this.SelfCheckBox = false;
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        var userId = localStorage.getItem('CisspUserId');
        var cer_id = localStorage.getItem('CisspCourseId');
        var cohort_id = localStorage.getItem('cohort_id');
        await this.ScheduleserviceService.getSelfSchedule(
          userId,
          cer_id,
          cohort_id,
          token
        ).then((data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            if (list.data.length > 0 && this.IsSelfPacedClass) {
              this.CustomeTitle = 'Create your own custom schedule';
              this.IsSelfSchedule = true;
              let vals = list.data[list.data.length - 1];
              this.self_schedule_id = vals.id;
              this.sun = vals.sun;
              this.mon = vals.mon;
              this.tues = vals.tues;
              this.wed = vals.wed;
              this.thurs = vals.thurs;
              this.fri = vals.fri;
              this.sat = vals.sat;
              this.hsun = vals.hsun;
              this.hmon = vals.hmon;
              this.htues = vals.htues;
              this.hwed = vals.hwed;
              this.hthurs = vals.hthurs;
              this.hfri = vals.hfri;
              this.hsat = vals.hsat;
            }
          }
        });
      }
    });
  }
  ReArrengeArray(sch) {
    if (this.IsSelfPacedClass) {
      let olddata = {
        DateStringcompleted_date: sch.DateStringcompleted_date,
        DateStringdue_date: '',
        DateStringoverdue_date: '',
        DateStringvalue: '',
        KA_access: sch.KA_access,
        cohort_id: sch.cohort_id,
        completed_date: sch.completed_date,
        createdAt: sch.createdAt,
        due_date: sch.due_date,
        due_number: sch.due_number,
        examname:
          sch.type == 'Event' ? 'Recoded Live Events' : 'Completed Schedule',
        id: sch.id,
        ketexam_name: sch.ketexam_name,
        knowass_name: sch.knowass_name,
        overdue_date: sch.overdue_date,
        overdue_number: sch.overdue_number,
        practice_name: sch.practice_name,
        required: sch.required,
        sortdate: '',
        status: sch.status,
        time: sch.time,
        ttlcomplete: sch.ttlcomplete,
        ttlq: sch.ttlq,
        ttlqpending: sch.ttlq - sch.ttlcomplete,
        type: 'title',
        type_id: sch.type_id,
        updatedAt: sch.updatedAt,
        typeVid: sch.typeVid,
        videolength: sch.videolength,
        percentage: sch.percentage,
        percentagecircle: sch.percentagecircle,
        datelable: sch.datelable,
        section_id: 100,
        ProgessPer: sch.ProgessPer,
        homework: sch.homework,
        event_url: sch.event_url,
        meeting_playform: sch.meeting_playform,
        title_type: 'Section',
        download_description: sch.download_description,
        download_url: sch.download_url,
      };
      return olddata;
    }
  }
  async BaselineData() {
    let lineData = this.sharedDataService.getBaselineData()
    if (lineData && lineData.length > 0) {
      this.selected_BaseLine_schedule = lineData[0];
      this.selected_BaseLine_schedule.type_id = lineData[0].id;
      this.selected_BaseLine_schedule.examname = lineData[0].examname;
      if (this.selected_BaseLine_schedule.ttlcomplete != 0) {
        this.selected_BaseLine_schedule.ProgessPer =
          100 *
          lineData[0].ttlcomplete *
          lineData[0].ttlq;
      }
      this.isBaseShowSchedule = true;
    } else {
      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 data = {
            user_id: localStorage.getItem('CisspUserId'),
            cohort_id: localStorage.getItem('cohort_id'),
          };
          await this.ScheduleserviceService.BaselineData(data, token).then(
            async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                if (list.data.length > 0) {
                  this.sharedDataService.setBaselineData(list.data)
                  this.selected_BaseLine_schedule = list.data[0];
                  this.selected_BaseLine_schedule.type_id = this.selected_BaseLine_schedule.id;
                  this.selected_BaseLine_schedule.examname = this.selected_BaseLine_schedule.examname + ' Knowledge Assessment';
                  if (this.selected_BaseLine_schedule.ttlcomplete != 0) {
                    this.selected_BaseLine_schedule.ProgessPer =
                      100 *
                      this.selected_BaseLine_schedule.ttlcomplete *
                      this.selected_BaseLine_schedule.ttlq;
                  }
                  this.isBaseShowSchedule = true;
                } else {
                  this.selected_BaseLine_schedule = {};
                  this.isBaseShowSchedule = false;
                }
              }
            }
          );
          await this.spinner.hide();
        }
      });
      await this.spinner.hide();
    }
  }
  validateNumber(e, item) {
    this.ShowSuffienttime = false;
    this.misMatchSchedule = false;
    var idx = e.target.value;
    if ((idx = 0)) {
      return false;
    } else if (e.target.value > 24) {
      e.target.value = 24;
      return false;
    } else if (e.target.value <= 0) {
      e.target.value = 0;
      if (item == 'sun') {
        this.sun = 0;
      } else if (item == 'mon') {
        this.mon = 0;
      } else if (item == 'tues') {
        this.tues = 0;
      } else if (item == 'wed') {
        this.wed = 0;
      } else if (item == 'thurs') {
        this.thurs = 0;
      } else if (item == 'fri') {
        this.fri = 0;
      } else {
        this.sat = 0;
      }
      return false;
    }
    return true;
  }
  formatZone(zone: string): TZone {
    const utc: string = momentZone.tz(zone).format('Z');
    const abbr: string = momentZone.tz(zone).zoneAbbr();
    return {
      name: `${zone} (${utc})`,
      nameValue: zone,
      timeValue: utc,
      group: zone.split('/', 1)[0],
      abbr: abbr,
    };
  }
  EventStart(item) {
    window.open(item.event_url, '_blank');
  }
  LiveClassEventChange() {
    this.calScheduleList.forEach((element) => {
      if (element.type == 'Events') {
        let timeZone = element.due_date.substr(element.due_date.length - 6, 6);
        let due_date = new Date();
        let overdue_date;
        let currTimeZone = this.auth.currentTimeZone();
        if (currTimeZone.timeValue != timeZone) {
          due_date = new Date(element.due_date);
          overdue_date = new Date(element.overdue_date);
        } else {
          due_date = new Date(
            new Date(element.due_date).toLocaleString('en-US', {
              timeZone: this.timezone,
            })
          );
          overdue_date = new Date(
            new Date(element.overdue_date).toLocaleString('en-US', {
              timeZone: this.timezone,
            })
          );
        }
        let curr_date = new Date(
          new Date().toLocaleString('en-US', { timeZone: this.timezone })
        );
        let meet_url = '#';
        if (new Date(due_date) > curr_date && element.is_completed != 1) {
          if (
            new Date(
              new Date(due_date).setMinutes(
                new Date(due_date).getMinutes() - 15
              )
            ) < curr_date
          ) {
            element.status = 'Comming Soon';
            if (element.meeting_playform == 2) {
              var eventstart = {
                id: element.id,
                title: element.examname,
                user_id: localStorage.getItem('CisspUserId'),
              };
              meet_url = environment.SITE_URL + '/startconference/' + encodeURIComponent(btoa(JSON.stringify(eventstart)));
              element.alreadyJoin = element.alreadyJoin;
            }
            if (element.meeting_playform == 1) {
              meet_url = element.event_url;
              element.alreadyJoin = 0;
            }
          } else {
            element.status = 'Not Started';
          }
        } else if (
          element.is_live == 1 ||
          (element.meeting_playform == 1 && new Date(due_date) < curr_date)
        ) {
          if (element.event_url && element.meeting_playform == 2) {
            meet_url = environment.SITE_URL + '/conference/' + encodeURIComponent(btoa(JSON.stringify(element.event_url)));
            element.status = 'Comming Soon';
            element.alreadyJoin = element.alreadyJoin;
          }
          if (element.event_url && element.meeting_playform == 1) {
            meet_url = element.event_url;
            element.alreadyJoin = 0;
          }
        } else if (
          element.is_completed == 1 ||
          (element.meeting_playform == 1 && new Date(overdue_date) < curr_date)
        ) {
          element.status = 'Completed';
          element.complete_date =
            element.meeting_playform == 2
              ? element.complete_date
              : new Date(
                this.auth.ConvertAnyTimeZoneToCurrentZone(
                  this.auth.ConvertFormatDbDateTime(
                    overdue_date,
                    this.timezone
                  ),
                  this.timezone
                )
              );
          element.completed_date =
            element.meeting_playform == 2
              ? element.complete_date
              : new Date(
                this.auth.ConvertAnyTimeZoneToCurrentZone(
                  this.auth.ConvertFormatDbDateTime(
                    overdue_date,
                    this.timezone
                  ),
                  this.timezone
                )
              );
        } else {
          element.status = 'Not Started';
        }
        element.event_time = due_date.toLocaleTimeString();
        element.event_url = meet_url;
      } else {
        element.section_id = element.id;
      }
    });
  }
  onVideoPercentUpdate(event) {
    let scheduleData = this.sharedDataService.getScheduleData()
    let status = "Not Started"
    if (event.percent >= 100) {
      status = "Completed"
    } else if (event.percent < 100 && event.percent != 0) {
      status = "In Progress"
    } else {
      status = "Not Started"
    }
    scheduleData.forEach(element => {
      if (element.material_type == 'Video' && element.material_id == event.id && element.status != 'Completed') {
        element.view_percent = event.percent;
        element.status = status;
      }
    });
    this.sharedDataService.setScheduleData(scheduleData)
  }
  popupClose(event) {
    let scheduleData = this.sharedDataService.getScheduleData()
    let status = "Not Started"
    if (event.percent >= 100) {
      status = "Completed"
    } else if (event.percent < 100 && event.percent != 0) {
      status = "In Progress"
    } else {
      status = "Not Started"
    }
    scheduleData.forEach(element => {
      if (element.material_type == 'Video' && element.material_id == event.id && element.status != 'Completed') {
        element.view_percent = event.percent;
        element.status = status;
      }
    });
    this.sharedDataService.setScheduleData(scheduleData)
    this.scduledataall();
    this.VideoPopup = false;
  }

  onMindmapPercentUpdate(event) {
    if (event.percent > 0) {
      let scheduleData = this.sharedDataService.getScheduleData()
      let status = "Not Started"
      if (event.percent >= 100) {
        status = "Completed"
      } else if (event.percent < 100 && event.percent != 0) {
        status = "In Progress"
      } else {
        status = "Not Started"
      }
      scheduleData.forEach(element => {
        if (element.material_type == 'Mindmap' && element.material_id == event.id && element.status != 'Completed') {
          element.view_percent = event.percent;
          element.status = status;
        }
      });
      this.sharedDataService.setScheduleData(scheduleData)
      this.scduledataall();
    }
  }
  MindmappopupClose(event) {
    if (event.percent > 0) {
      let scheduleData = this.sharedDataService.getScheduleData()
      let status = "Not Started"
      if (event.percent >= 100) {
        status = "Completed"
      } else if (event.percent < 100 && event.percent != 0) {
        status = "In Progress"
      } else {
        status = "Not Started"
      }
      scheduleData.forEach(element => {
        if (element.material_type == 'Mindmap' && element.material_id == event.id && element.status != 'Completed') {
          element.view_percent = event.percent;
          element.status = status;
        }
      });
      this.sharedDataService.setScheduleData(scheduleData)
      this.scduledataall();
    }
    this.MindmapPopup = false;
  }
  backwordvideo() {
    const video = document.getElementsByTagName('video');
    video[0].currentTime = video[0].currentTime - 10;
  }

  forwordvideo() {
    const video = document.getElementsByTagName('video');
    video[0].currentTime = video[0].currentTime + 10;
  }
  changeplay() {
    if (this.api.state == 'paused') this.api.play();
    if (this.api.state == 'playing') this.api.pause();
  }
  onPlayerReady(api: VgApiService) {
    this.api = api;
    this.playback = this.api.playbackRate;
    let me = this
    document.onkeydown = function (event) {
      const video = document.getElementsByTagName('video');
      switch (event.keyCode) {
        case 37://ArrowLeft-  Backward 10 sec
          video[0].currentTime = video[0].currentTime - 10;
          break;
        case 38://ArrowUp- volume increase
          if (video[0].volume != 1)
            video[0].volume += 0.1;
          break;
        case 39://ArrowRight- Forward 10 sec
          video[0].currentTime = video[0].currentTime + 10;
          break;
        case 40://ArrowDown- Volume decrease
          if (video[0].volume > 0.1)
            video[0].volume -= 0.1;
          break;
        case 32://SpaceBar- Play Pause
          event.preventDefault();
          video[0].paused ? video[0].play() : video[0].pause();
          break;
        case 70://F- Fullscreen
          me.api.fsAPI.toggleFullscreen()
          break;
        case 74://J- Backward 10 sec
          video[0].currentTime = video[0].currentTime - 10;
          break;
        case 75://K- Play Paused
          video[0].paused ? video[0].play() : video[0].pause();
          break;
        case 76://L- Forward 10 sec
          video[0].currentTime = video[0].currentTime + 10;
          break;
        case 77://M- Mute Unmute
          video[0].volume = video[0].volume == 1 ? 0 : 1;
          break;
        case 188://<- Slod down video playback rate
          if (video[0].playbackRate > 0.25)
            video[0].playbackRate -= 0.25
          me.playbackRate(video[0].playbackRate)
          break;
        case 190://>- Speedup video playback rate
          video[0].playbackRate += 0.25
          me.playbackRate(video[0].playbackRate)
          break;

      }
    };
  }
  playbackRate(item) {
    this.selectedPlaybackSpeed = item == 1 ? "Normal" : item;
  }
  calendar(item, type) {
    const options: CalendarOptions = {
      title: item.examname,
      description: item.examname,
      start: new Date(item.due_date),
      end: new Date(
        new Date(item.due_date).setMinutes(
          new Date(item.due_date).getMinutes() + item.event_minutes
        )
      ),
    };
    if (type == 'g') {
      const googleCalendar = new GoogleCalendar(options);
      window.open(googleCalendar.render());
    }
    if (type == 'o') {
      const outlookcalendar = new OutlookCalendar(options);
      window.open(outlookcalendar.render());
    }
    if (type == 'y') {
      const yahoocalendar = new YahooCalendar(options);
      window.open(yahoocalendar.render());
    }
    if (type == 'o3') {
      const outlookcalendar = new OutlookCalendar(options);
      window.open(outlookcalendar.render());
    }
    if (type == 'i') {
      const icalendar = new ICalendar(options);
      icalendar.download(item.examname + '.ics');
    }
  }
  getFlashcardCount(array) {
    let group = this.groupByArray(array, 'each_flashcard_day');
    let sum = 0;
    for (const key in group) {
      sum += key != 'NaN' ? parseInt(key) : 0;
    }
    return sum;
  }
  getPracticeAppCount(array) {
    let group = this.groupByArray(array, 'each_PQA_day');
    let sum = 0;
    for (const key in group) {
      sum += key != 'NaN' ? parseInt(key) : 0;
    }
    return sum;
  }
  async downloadMaterial(item) {
    this.spinner.show();
    await this.ScheduleserviceService.downloadMaterial(item.download_url, item.examname)
    this.spinner.hide();
  }
}
export interface supportList {
  certi_id: number;
  duration: number;
  event_id: string;
  id: string;
  meeting_id: string;
  play_list: any;
  title: string;
  createdAt: string;
  recording_url: string;
  questions: any;
}

export interface upcomingEventDetail {
  "examname": string;
  "type": string;
  "cohort_id": string;
  "due_date": any;
  "overdue_date": string;
  "event_duration": any;
  "event_time": any;
  "event_url": any;
  "end_time": any;
  "status": string;
  "time": any;
  "id": number;
  "event_time_zone": any;
  "complete_date": any;
  "meeting_playform": any;
  "is_completed": any;
  "is_live": any;
  "alreadyJoin": any;
  "is_repeat": any;
  "repeat_count": any;
  "repeat_type": any;
  "repeat_on": any;
  "ends_on": any;
  "ends_type": any;
  "total_occurances": any;
  "end_date": any;
  "ev_date": any;
}