import { Component, ViewChild } from '@angular/core';
import * as d3 from 'd3';
import * as d3Shape from 'd3';
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { AuthserviceService } from '../../authservice.service';
import { Router } from '@angular/router';
import { DashboardserviceService } from '../../services/dashboard/dashboardservice.service';
import { CourseserviceService } from 'src/app/services/course/courseservice.service';
import { ScheduleserviceService } from '../../services/Schedule/scheduleservice.service';
import * as momentZone from 'moment-timezone';
import { TZone } from 'moment-timezone-picker';
import { SharedDataService } from 'src/app/services/SharedData/shared-data.service';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss'],
})
export class DashboardComponent {
  PaymentAccess: boolean = false;
  @ViewChild('content', { static: false }) private content: Element;
  leaderboardModal: boolean = false;
  Activities = [];
  LeaderBoard = [];
  StartDisabled: boolean = true;
  OverdueText: any;
  CurrentPoint: any;
  ImproveTotalPoint: number = 0;
  ImproveAvatar: any;
  CurrentName: any;
  CurrentRank: any;
  CurrentOpt_in: any;
  ScoreImprove = [];
  imgurl: any;
  Overall: any;
  TotalSvg: any;
  VideoPopup: boolean = false;
  MindmapPopup: boolean = false;
  openMindMap: boolean = false;
  // schedule
  ScheduleList = [];
  bkpScheduleList = [];
  calScheduleList = [];
  IsSelfSchedule: boolean = true;
  self_schedule_id: any;
  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;
  exam_date: any;
  study_date: any;
  enddate: Date;
  startdate: Date;
  changeDate: Boolean = false;
  GetDate: any;
  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;
  noOfMin: number = 0;
  calKATime: number = 45;
  calPracticeTime: number = 45;
  calCatTime: number = 45;
  CalOtherTime: number = 45;
  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;
  main_title_id: any;
  SelfScheduleTime: number = 0;
  isNotSelfSchedualTime: number = 420;
  ErrorSelfSchedule: number = 0;

  title = 'dstn-dashboard';
  private width = 1350;
  private height = 1020;
  private data = [];
  private x: any;
  private y: any;
  private svg: any;
  private line: d3Shape.Line<[number, number]>;
  l: any;
  domainsData = JSON.parse(localStorage.getItem('domainsData'));
  treeTendData = [
    {
      x: -80,
      y: 567,
      width: 600,
      src: '../../../assets/dashboard/img-bushes-111.png',
    },
    {
      y: 78,
      x: 33,
      width: 137,
      src: '../../../assets/dashboard/img-hut-chimneysmoke.png',
    },
    {
      y: 221,
      x: 990,
      width: 347,
      src: '../../../assets/dashboard/img-mountain-trees.png',
    },
    {
      x: 300,
      y: 392,
      width: 200,
      src: '../../../assets/dashboard/img-trees-tent-1.png',
    },
    {
      y: 491,
      x: 875,
      width: 290,
      src: '../../../assets/dashboard/img-trees-tent-2.png',
    },
  ];
  passedPro: any;
  path: any;
  pathLen: any;
  speed: any;
  closeResult: any;
  showModalF: Boolean;
  modal: any;
  private totalProSvg: any;
  modalData: any;
  scheduleDomain: any;
  constructor(
    public service: ServicesService,
    private spinner: NgxSpinnerService,
    private auth: AuthserviceService,
    private router: Router,
    public ScheduleserviceService: ScheduleserviceService,
    private DashboardserviceService: DashboardserviceService,
    public CourseserviceService: CourseserviceService,
    public sharedDataService: SharedDataService
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
    this.getResult();
    this.service.headerset = {
      dashboard: true,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      knowques: false,
      knowresult: false,
      CATresult: false,
      CATQue: false,
      studentprofile: false,
      PracticeResult: false,
      Practiceques: false,
      resource: false,
      liveSupport: false,
    };
    this.service.headershow = true;
  }
  scoreBoard() {
    this.leaderboardModal = true;
  }
  closeBoard() {
    this.leaderboardModal = false;
  }
  private addXandYAxis() {
    // range of data configuring
    this.x = d3
      .scaleLinear()
      .domain(d3.extent(this.data, (d) => parseFloat(d.x)))
      .nice()
      .range([0, this.width]);
    this.y = d3
      .scaleLinear()
      .domain(d3.extent(this.data, (d) => parseFloat(d.y)))
      .nice()
      .range([this.height, 0]);
  }
  private createSvg(): void {
    this.svg = d3.select('#svg-route');
  }
  private drawLineAndPath() {
    const passed = this.passedPro / 100;
    this.line = d3
      .line()
      .curve(d3.curveCatmullRom)
      .x((d: any) => this.x(d.x) - 20)
      .y((d: any) => this.y(d.y) - 20);
    this.svg
      .append('path')
      .datum(this.data)
      .attr('class', 'line')
      .attr('d', this.line)
      .attr('id', 'path-back')
      .attr('background', '#000')
      .attr('stroke', '#fff')
      .attr('stroke-miterlimit', '10')
      .attr('stroke-width', '2')
      .attr('stroke-dasharray', '4 3.1')
      .attr('fill', 'none');
    this.path = this.svg
      .append('path')
      .datum(this.data)
      .attr('class', 'line')
      .attr('d', this.line)
      .attr('id', 'path')
      .attr('stroke', '#8c90a630')
      .attr('stroke-miterlimit', '0')
      .attr('stroke-width', '12')
      .attr('fill', 'none');
    this.pathLen = this.path.node().getTotalLength();
    const passedPath = this.svg
      .append('path')
      .datum(this.data)
      .attr('class', 'passed-line')
      .attr('d', this.line)
      .attr('id', 'pathPink')
      .attr('stroke', '#F0F')
      .attr('stroke-miterlimit', '10')
      .attr('stroke-width', '2')
      .attr('stroke-dasharray', '4 3.1')
      .attr('fill', 'none')
      .attr('stroke-dasharray', this.pathLen);
  }
  private async drawDomains() {
    let pro = 100;
    if (localStorage.getItem('method') != '0') {
      await this.getScheduleDomain();
    }
    let p;
    await this.getScheduleDomain();
    let filteredArray = this.scheduleDomain?.map((item) => {
      const domainNumber = parseInt(item.title_name.match(/\d+/)[0]);
      return domainNumber;
    });
    for (let i = this.domainsData.length; i > 0; i--) {
      function customSort(a, b) {
        return filteredArray?.indexOf(a.num) - filteredArray?.indexOf(b.num);
      }
      this.domainsData.sort(customSort);
      pro -= this.domainsData[i - 1].weight;
      p = this.path.node().getPointAtLength((this.pathLen * pro) / 100);
      this.svg
        .append('circle')
        .attr('r', '10')
        .attr('cx', p.x)
        .attr('cy', p.y)
        .attr('stroke', pro > this.passedPro ? '#ffffff' : '#FF5A9B')
        .attr('stroke-width', '2.5')
        .attr('fill', '#e5a0d9')
        .attr('id', 'domain-path-pos-wrapper' + i)
        .attr('class', 'domain-path-pos-wrapper');
      this.svg
        .append('circle')
        .attr('r', '2.5')
        .attr('cx', p.x)
        .attr('cy', p.y)
        .attr('stroke', pro > this.passedPro ? '#ffffff' : '#FF5A9B')
        .attr('fill', pro > this.passedPro ? '#ffffff' : '#FF5A9B')
        .attr('stroke-width', '3')
        .attr('id', 'domain-path-pos-core' + i)
        .attr('class', 'domain-path-pos-core');
      this.svg
        .append('rect')
        .attr('width', '47')
        .attr('height', '129')
        .attr('x', p.x - 25)
        .attr('y', p.y - 129)
        .attr('fill', 'url(#grad1)')
        .attr('id', 'domain-main-back' + i)
        .attr('class', 'domain-back-rec rectangle');
      const domainBack = this.svg
        .append('image')
        .attr('width', '49')
        .attr('x', p.x - 26)
        .attr('y', p.y - 154)
        .attr(
          'href',
          pro > this.passedPro
            ? '../../../assets/dashboard/domain-back.png'
            : '../../../assets/dashboard/domain-back-pink.png'
        )
        .attr('id', 'domain-back' + i)
        .attr('class', 'domain domain-back');
      domainBack.node().onclick = (event) => this.showModal(i, event);
      domainBack
        .node()
        .animate(
          [
            { transform: 'translateY(' + 0 + 'px)' },
            { transform: 'translateY(' + 5 + 'px)' },
            { transform: 'translateY(' + 0 + 'px)' },
          ],
          {
            duration: 2000,
            iterations: Infinity,
          }
        );
      const domainPro = this.svg
        .append('circle')
        .attr('r', '21')
        .attr('cx', p.x - 2)
        .attr('cy', p.y - 130)
        .attr('fill', 'transparent')
        .attr('stroke', '#c9459f')
        .attr('stroke-width', '5')
        .attr(
          'stroke-dasharray',
          this.domainsData[i - 1].totalPro * 1.31 +
          ' ' +
          (100 - this.domainsData[i - 1].totalPro) * 1.31
        )
        .attr('stroke-dashoffset', '33')
        .attr('class', 'domainPro' + i);
      domainPro.node().onclick = (event) => this.showModal(i, event);
      domainPro
        .node()
        .animate(
          [
            { transform: 'translateY(' + 0 + 'px)' },
            { transform: 'translateY(' + 5 + 'px)' },
            { transform: 'translateY(' + 0 + 'px)' },
          ],
          {
            duration: 2000,
            iterations: Infinity,
          }
        );
      const domainCoreBack = this.svg
        .append('circle')
        .attr('r', '18')
        .attr('cx', p.x - 2)
        .attr('cy', p.y - 130)
        .attr('fill', '#ea0079')
        .attr('id', 'domain-core-back' + i)
        .attr('class', 'domain domain-core-back');
      domainCoreBack.node().onclick = (event) => this.showModal(i, event);
      domainCoreBack
        .node()
        .animate(
          [
            { transform: 'translateY(' + 0 + 'px)' },
            { transform: 'translateY(' + 5 + 'px)' },
            { transform: 'translateY(' + 0 + 'px)' },
          ],
          {
            duration: 2000,
            iterations: Infinity,
          }
        );
      const domainLabel = this.svg
        .append('text')
        .attr('x', p.x - 12)
        .attr('y', p.y - 126)
        .attr('id', 'domain-val' + i)
        .attr('fill', '#fff')
        .attr('font-size', '15')
        .attr('font-family', "'Roboto', sans-serif")
        .attr('font-weight', 'bold')
        .attr('style', 'width: 38px; height: 38px; text-align: center;')
        .attr('class', 'domain domain-value')
        .text('M' + this.domainsData[i - 1].num);
      domainLabel.node().onclick = (event) => this.showModal(i, event);
      domainLabel
        .node()
        .animate(
          [
            { transform: 'translateY(' + 0 + 'px)' },
            { transform: 'translateY(' + 5 + 'px)' },
            { transform: 'translateY(' + 0 + 'px)' },
          ],
          {
            duration: 2000,
            iterations: Infinity,
          }
        );
    }
    var sheet = document.createElement('style');
    sheet.innerHTML = '.domain { cursor: pointer }';
    document.body.appendChild(sheet);
  }
  private drawHiker() {
    const length = this.pathLen;
    const passed = this.passedPro / 100;
    this.svg
      .append('image')
      .attr('width', '46')
      .attr('href', '../../../assets/dashboard/hiker-left.png')
      .attr('id', 'hiker');
    let oldPosition;
    let me = this;
    const dot = {
      sprite: null,
      track: null,
      svg: null,
      // Initialize the dot: connect sprite and track properties with supplied SVG elements
      init: function (sprite, track) {
        this.sprite = document.getElementById(sprite);
        let data = document.getElementById('svg-route');
        this.track = data.querySelector(track);
        this.svg = d3.select('#svg-route');
      },
      alpha: function (oldPos, newPos) {
        const a = Math.abs(oldPos.x - newPos.x) * 1.5;
        const b = Math.abs(oldPos.y - newPos.y);
        return a > b ? false : true;
      },
      isMountain: function (pro) {
        return (pro > 85 && pro < 87) || pro > 93 ? true : false;
      },
      // Put the dot on its spot
      move: function (u) {
        const p = this.track.getPointAtLength(u * length * passed);
        if (oldPosition === undefined) {
          oldPosition = p;
        }
        if (this.alpha(oldPosition, p)) {
          if (this.isMountain(u * passed * 100)) {
            u === 1
              ? this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/icon-char_back_rear1.png'
              )
              : this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/hiker-up1.png'
              );
          } else {
            u === 1
              ? this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/icon-char_back1.png'
              )
              : this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/hiker-up.png'
              );
          }
        } else if (oldPosition.x > p.x) {
          if (this.isMountain(u * passed * 100)) {
            u === 1
              ? this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/icon-char_left_rear1.png'
              )
              : this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/hiker-left1.png'
              );
          } else {
            u === 1
              ? this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/icon-char_left1.png'
              )
              : this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/hiker-left.png'
              );
          }
        } else if (oldPosition.x < p.x) {
          if (this.isMountain(u * passed * 100)) {
            u === 1
              ? this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/icon-char_right_rear1.png'
              )
              : this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/hiker-right1.png'
              );
          } else {
            u === 1
              ? this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/icon-char_right1.png'
              )
              : this.sprite.setAttribute(
                'href',
                '../../../assets/dashboard/hiker-right.png'
              );
          }
        }
        if (
          (u * passed * 100 > 56.5 && u * passed * 100 < 58.7) ||
          (u * passed * 100 > 74 && u * passed * 100 < 75)
        )
          this.sprite.setAttribute('href', '');
        if (u === 1) {
          const marker = this.svg
            .append('image')
            .attr(
              'href',
              '../../../assets/dashboard/icon-marker_pointer_yellow.png'
            )
            .attr('id', 'hiker')
            .attr('x', p.x - 12)
            .attr('y', this.isMountain(passed * 100) ? p.y - 100 : p.y - 120);
          marker
            .node()
            .animate(
              [
                { transform: 'translateY(' + -5 + 'px)' },
                { transform: 'translateY(' + 0 + 'px)' },
                { transform: 'translateY(' + 5 + 'px)' },
                { transform: 'translateY(' + 0 + 'px)' },
                { transform: 'translateY(' + 5 + 'px)' },
                { transform: 'translateY(' + 5 + 'px)' },
                { transform: 'translateY(' + 5 + 'px)' },
              ],
              {
                duration: 1500,
                iterations: Infinity,
              }
            );
        }
        oldPosition = p;
        this.sprite.setAttribute(
          'transform',
          `translate(${p.x - 23}, ${p.y - 130})`
        );
        this.sprite.scrollIntoView({
          block: 'center',
          inline: 'center',
        });
        if (passed * u === 1) {
          this.sprite.setAttribute(
            'href',
            '../../../assets/dashboard/hiker-final.png'
          );
          this.sprite.setAttribute(
            'transform',
            `translate(${p.x - 33}, ${p.y - 70})`
          );
        }
      },
    };
    const anim = {
      start: function (duration) {
        this.duration = duration;
        this.tZero = Date.now();
        requestAnimationFrame(() => this.run());
      },
      run: function () {
        let u = Math.min((Date.now() - this.tZero) / this.duration, 1);
        if (u < 1) {
          // Keep requesting frames, till animation is ready
          requestAnimationFrame(() => this.run());
        } else {
          u = 1;
        }
        dot.move(u);
      },
      onFinish: function () {
        // Schedule the animation to restart
        setTimeout(() => this.start(this.duration), 1000);
      },
    };
    dot.init('hiker', 'path');
    anim.start(this.speed * this.passedPro);
    const sheet = document.createElement('style');
    sheet.innerHTML =
      '.passed-line { stroke-dasharray: ' +
      this.pathLen +
      '; stroke-dashoffset: ' +
      this.pathLen +
      '; animation: dash ' +
      this.speed * 0.001 * this.passedPro +
      's linear forwards;} @keyframes dash {to {stroke-dashoffset: ' +
      this.pathLen * (1 - this.passedPro / 100) +
      ';}}';
    document.body.appendChild(sheet);
    for (let i = 1; i < this.domainsData.length + 1; i++) {
      const sheet1 = document.createElement('style');
      sheet1.innerHTML =
        '.domainPro' +
        i +
        ' { stroke-dasharray: 0 131' +
        '; stroke-dashoffset: 33' +
        '; animation: dash' +
        i +
        ' ' +
        this.speed * 0.0003 * this.domainsData[i - 1].totalPro +
        's linear forwards;} @keyframes dash' +
        i +
        ' {to {stroke-dasharray: ' +
        this.domainsData[i - 1].totalPro * 1.31 +
        ' ' +
        (100 - this.domainsData[i - 1].totalPro) * 1.31 +
        ';}}';
      document.body.appendChild(sheet1);
    }
  }
  private drawTreeTent() {
    for (let i = 0; i < this.treeTendData.length; i++) {
      this.svg
        .append('image')
        .attr('x', this.treeTendData[i].x)
        .attr('y', this.treeTendData[i].y)
        .attr('width', this.treeTendData[i].width)
        .attr('href', this.treeTendData[i].src);
    }
  }
  showModal(nth, evt) {
    let filteredArray = this.scheduleDomain?.map((item) => {
      const domainNumber = parseInt(item.title_name.match(/\d+/)[0]);
      return domainNumber;
    });
    function customSort(a, b) {
      return filteredArray?.indexOf(a.num) - filteredArray?.indexOf(b.num);
    }
    this.domainsData.sort(customSort);
    this.modalData = this.domainsData[nth - 1];
    let pro = 100;
    let p;
    for (let i = this.domainsData.length; i > nth - 1; i--) {
      pro -= this.domainsData[i - 1].weight;
    }
    p = this.path.node().getPointAtLength((this.pathLen * pro) / 100);
    if (window.innerWidth - p.x < 400) {
      this.modal.node().setAttribute('class', 'left-mode');
    } else {
      this.modal.node().removeAttribute('class');
    }
    const x = evt.offsetX + 30;
    const y = evt.offsetY - 30;
    this.modal
      .node()
      .setAttribute(
        'style',
        'display: block; position: absolute; top: ' +
        y +
        'px; left: ' +
        x +
        'px;'
      );
    this.totalProSvg = d3.select('#total-pro');
    this.totalProSvg.select('#passed').remove();
    if (this.modalData.totalPro > 0) {
      this.totalProSvg
        .append('circle')
        .attr(
          'stroke-dasharray',
          this.modalData.totalPro + ' ' + (100 - this.modalData.totalPro)
        )
        .attr('class', 'passed')
        .attr('id', 'passed');
    }
    for (let i = 0; this.modalData.subPros.length > i; i++) {
      let dasharr =
        this.modalData.subPros[i].val +
        ' ' +
        (100 - this.modalData.subPros[i].val);
      const id = '#sub-pro' + i;
      let subProSvg = d3.select(id);
      subProSvg.select('#passed' + i).remove();
      if (this.modalData.subPros[i].val > 0) {
        subProSvg
          .append('circle')
          .attr('stroke-dasharray', dasharr)
          .attr('class', 'sub-passed')
          .attr('id', 'passed' + i);
      }
    }
  }
  private createDetailsModal() {
    this.modal = d3.select('#detailsModal');
    this.modal.node().setAttribute('style', 'display: none');
    this.modalData = this.domainsData[0];
  }
  async ngOnInit(): Promise<void> {
    this.listCourses();
    if (localStorage.getItem('course_type') == 'Free') {
      this.PaymentAccess = true;
    } else {
      this.PaymentAccess = false;
    }
    this.createSvg();
    this.createDetailsModal();
    let sum = 0;
    let i = 0;
    let w = [9, 11, 12, 12, 12, 12, 12, 12];
    this.domainsData.forEach((element) => {
      element.weight = w[i];
      i++;
      sum += element.totalPro;
    });
    this.Overall = localStorage.getItem('overall');
    this.passedPro = this.Overall;
    var TotalSvg = this.Overall + ' ' + (100 - this.Overall);
    this.TotalSvg = TotalSvg ? TotalSvg : 0;
    this.speed = 150;
    this.showModalF = false;
    d3.csv('../../../assets/path.csv').then((data) => {
      this.data = data;
      this.addXandYAxis();
      this.drawLineAndPath();
      this.drawHiker();
      this.drawTreeTent();
      this.drawDomains();
    });
    window.addEventListener('mouseup', function (event) {
      var pol = document.getElementById('detailsModal');
      if (event.target != pol && pol !== null) {
        pol.style.display = 'none';
      }
    });
    setTimeout(async () => {
      this.service.headershow = true;
      this.service.SearchValue = true;
      this.service.title =
        "<p class='HeaderUser'>My <span>Dashboard </span></p>";
    }, 600);
    this.getDashActivities();
    this.getLeaderBoard();
    this.scoreImprove();
    var data = localStorage.getItem('userdetails');
    if (data != undefined || data != null || data != '') {
      this.data = JSON.parse(<string>data);
      this.imgurl = this.data['avatar_url'];
    }
    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;
      }
    }
    if (localStorage.getItem('method') != '0') {
      await this.getScheduleDomain();
      await this.getAllComponentTime();
      await this.getSelfSchedule(0);
      await this.scduledataall();
    }
  }
  async listCourses() {
    try {
      await this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            var token = session
            var user_id = +localStorage.getItem('CisspUserId');
            var cohort_id = localStorage.getItem('cohort_id');
            await this.CourseserviceService.knowassquecource(
              user_id,
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                var courselist = list.data.filter(
                  (x) => x.cohort_id == cohort_id
                );
                if (courselist.length > 0) {
                  localStorage.setItem('overall', courselist[0].percentage);
                  this.Overall = localStorage.getItem('overall');
                  this.passedPro = this.Overall;
                  var TotalSvg = this.Overall + ' ' + (100 - this.Overall);
                  this.TotalSvg = TotalSvg ? TotalSvg : 0;
                }
              }
              await this.spinner.hide();
            });
          }
        });
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }
  }
  async getDashActivities() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        let user_id = localStorage.getItem('CisspUserId');
        var cer_id = localStorage.getItem('CisspCourseId');
        if (localStorage.getItem('method') == '0') {
          this.IsSelfSchedule = false;
          await this.DashboardserviceService.getDashActivities(
            user_id,
            cer_id,
            token
          ).then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              if (list.data != null) {
                if (list.data[0]) {
                  list.data[0].forEach((element) => {
                    if (element.due_date) {
                      var GivenDate = new Date(element.due_date);
                      var CurrentDate = this.auth.ConvertDateDDFormat(
                        new Date(),
                        this.timezone,
                        'YYYY-MM-DD'
                      );
                      GivenDate = new Date(GivenDate);
                      let dt = new Date(CurrentDate).getTime() - GivenDate.getTime();
                      let days = Math.round(dt / (1000 * 60 * 60 * 24));
                      if (days == 0) {
                        element['OverdueText'] = '';
                        element['btntext'] =
                          element.resume == 0 ? 'Start' : 'Resume';
                        element['StartDisabled'] = false;
                      } else if (days < 0) {
                        if (days < 0 && -3 <= days) {
                          element['OverdueText'] =
                            'Upcoming in ' + Math.abs(days) + ' days';
                          element['StartDisabled'] = true;
                          element.status = 'Not Started'
                        } else {
                          element['btntext'] = element.resume == 0 ? 'Start' : 'Resume';
                          element['StartDisabled'] = false;
                        }
                      } else if (days > 0) {
                        if (3 > days) {
                          element['OverdueText'] = 'Overdue by ' + days + ' days';
                          element['StartDisabled'] = true;
                          if (element.status == 'Not Started') {
                            element['status'] = 'Overdue';
                          }
                        } else {
                          element['OverdueText'] = '';
                          element['btntext'] =
                            element.resume == 0 ? 'Start' : 'Resume';
                          element['StartDisabled'] = false;
                        }
                      }
                      if (element.status == 'Completed') {
                        element['OverdueText'] = element.status;
                        element['StartDisabled'] = true;
                      }
                      let invDate = new Date(element.due_date);
                      let invDate1 = invDate.toString().substring(4, 15);
                      element.due_date = invDate1;
                      let check = this.Activities.filter(
                        (x) =>
                          x.type == element.type && x.type_id == element.type_id
                      );
                      if (check.length <= 0) {
                        this.Activities.push(element);
                      }
                    }
                  });
                }
                this.Activities.sort(
                  (a, b) =>
                    new Date(a.due_date).getTime() -
                    new Date(b.due_date).getTime()
                );
                // show the current date content at the top of the schedule dashboard activity
                const currentdate = new Date();
                const firstHalf = this.Activities.filter((item) => {
                  const dateObject = new Date(item.due_date);
                  const year = dateObject.getFullYear();
                  const month = String(dateObject.getMonth() + 1).padStart(2, '0');
                  const day = String(dateObject.getDate()).padStart(2, '0');
                  const due_date = `${year}-${month}-${day}`;
                  return (
                    due_date <
                    this.auth.ConvertDateDDFormat(
                      currentdate,
                      this.timezone,
                      'YYYY-MM-DD'
                    )
                  );
                });
                const secondHalf = this.Activities.filter((item) => {
                  const dateObject = new Date(item.due_date);
                  const year = dateObject.getFullYear();
                  const month = String(dateObject.getMonth() + 1).padStart(2, '0');
                  const day = String(dateObject.getDate()).padStart(2, '0');
                  const due_date = `${year}-${month}-${day}`;
                  return (
                    due_date >=
                    this.auth.ConvertDateDDFormat(
                      currentdate,
                      this.timezone,
                      'YYYY-MM-DD'
                    )
                  );
                });
                const newActivities = secondHalf.concat(firstHalf);
                this.Activities = newActivities;
              }
            } else {
            }
          });
        }
      }
    });
  }
  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.IsSelfSchedule) {
              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;
              if (this.IsSelfSchedule) {
                let hrs = 0;
                let oldDate = '';
                this.ScheduleList.forEach((sch, i) => {
                  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);
                    } else {
                      hrs =
                        hrs +
                        (parseInt(sch.time.split(':')[0]) +
                          sch.time.split(':')[1] / 60);
                    }
                    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,
                        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,
                        alreadyJoin: sch.alreadyJoin,
                      };
                      this.bkpScheduleList.push(olddata);
                    }
                  } else {
                    this.bkpScheduleList.push(sch);
                  }
                  if (i == this.calScheduleList.length - 1)
                    this.enddate = new Date(oldDate);
                });
              }
            }
          }
        });
      }
      this.spinner.hide();
    });
  }
  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;
  }
  async selfPacedAfterApiCall(scheduleData) {
    this.sharedDataService.setScheduleData(scheduleData)
    this.calScheduleList = [];
    this.calScheduleList = scheduleData;
    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'];
          }
        }
      });
      var scheduldata = this.calScheduleList.filter((x) => x.due_date);
      this.ScheduleList = scheduldata;
      if (this.IsSelfSchedule) {
        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 (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);
            } 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);
            }
            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,
                  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,
                    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,
                  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,
                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,
                  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 domainGroup = [];
      let currentDomain = null;
      let currentDomainArray = [];
      let startIndex = this.ScheduleList.findIndex((item) =>
        item.examname.startsWith('Material')  || null
      );
      if (startIndex >= 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) => {
          const 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['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.IsSelfSchedule) {
                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.IsSelfSchedule) {
          }
          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');
      }
    });
    const Activities = this.ScheduleList.reduce((result, obj) => {
      if (
        obj.type == 'VideoLesson' && obj.belong_to ||
        obj.type == 'KA' ||
        obj.type == 'MindMap' ||
        obj.type == 'PRACTICE' ||
        obj.type == 'Test_revision' ||
        obj.type == 'KA_revision'
      ) {
        result.push(obj);
      }
      return result;
    }, []);
    if (Activities) {
      await Activities.forEach((element) => {
        if (element.createdAt) {
          var GivenDate = new Date(element.due_date);
          var CurrentDate = this.auth.ConvertDateDDFormat(
            new Date(),
            this.timezone,
            'YYYY-MM-DD'
          );
          GivenDate = new Date(GivenDate);
          let dt = new Date(CurrentDate).getTime() - GivenDate.getTime();
          let days = Math.floor(dt / (1000 * 60 * 60 * 24));
          if (days == 0) {
            element['OverdueText'] = '';
            element['btntext'] =
              element.status == 'Not Started' ||
                element.status == 'Overdue'
                ? (element.type == 'VideoLesson' || element.type == 'MindMap') &&
                  element.ProgessPer == 0
                  ? 'Play'
                  : element.type == 'KA' && element.ProgessPer == 0 ||
                    element.type == 'KA_revision' && element.ProgessPer == 0 ||
                    element.type == 'PRACTICE' && element.ProgessPer == 0 ||
                    element.type == 'Test_revision' && element.ProgessPer == 0
                    ? 'Start'
                    : 'Resume'
                : 'Resume';
            element['StartDisabled'] = false;
          } else if (days < 0) {
            if (days < 0 && -3 <= days) {
              element['OverdueText'] =
                'Upcoming in ' + Math.abs(days) + ' days';
              element['StartDisabled'] = true;
            } else {
              element['OverdueText'] = '';
              element['btntext'] =
                element.status == 'Not Started' ||
                  element.status == 'Overdue'
                  ? (element.type == 'VideoLesson' ||
                    element.type == 'MindMap') &&
                    element.ProgessPer == 0
                    ? 'Play'
                    : element.type == 'KA' && element.ProgessPer == 0 ||
                      element.type == 'KA_revision' && element.ProgessPer == 0 ||
                      element.type == 'PRACTICE' && element.ProgessPer == 0 ||
                      element.type == 'Test_revision' && element.ProgessPer == 0
                      ? 'Start'
                      : 'Resume'
                  : 'Resume';
              element['StartDisabled'] = false;
            }
          } else if (days > 0) {
            if (3 > days) {
              element['OverdueText'] = 'Overdue by ' + days + ' days';
              element['StartDisabled'] = true;
              if (element.status == 'Not Started') {
                element['status'] = 'Overdue';
              }
            } else {
              element['OverdueText'] = '';
              element['btntext'] =
                element.status == 'Not Started' ||
                  element.status == 'Overdue'
                  ? (element.type == 'VideoLesson' || element.type == 'MindMap') &&
                    element.ProgessPer == 0
                    ? 'Play'
                    : element.type == 'KA' && element.ProgessPer == 0 ||
                      element.type == 'KA_revision' && element.ProgessPer == 0 ||
                      element.type == 'PRACTICE' && element.ProgessPer == 0 ||
                      element.type == 'Test_revision' && element.ProgessPer == 0
                      ? 'Start'
                      : 'Resume'
                  : 'Resume';
              element['StartDisabled'] = false;
            }
          }
          if (element.status == 'Completed') {
            element['OverdueText'] = element.status;
            element['StartDisabled'] = true;
          }
        }
      });
    }
    const currentdate = new Date();
    const firstHalf = Activities.filter((item) => {
      const dateObject = new Date(item.due_date);
      const year = dateObject.getFullYear();
      const month = String(dateObject.getMonth() + 1).padStart(2, '0');
      const day = String(dateObject.getDate()).padStart(2, '0');
      const due_date = `${year}-${month}-${day}`;
      return (
        due_date < this.auth.ConvertDateDDFormat(
          currentdate,
          this.timezone,
          'YYYY-MM-DD'
        )
      );
    });
    const secondHalf = Activities.filter((item) => {
      const dateObject = new Date(item.due_date);
      const year = dateObject.getFullYear();
      const month = String(dateObject.getMonth() + 1).padStart(2, '0');
      const day = String(dateObject.getDate()).padStart(2, '0');
      const due_date = `${year}-${month}-${day}`;
      return (
        due_date >= this.auth.ConvertDateDDFormat(
          currentdate,
          this.timezone,
          'YYYY-MM-DD'
        )
      );
    });
    const newActivities = secondHalf.concat(firstHalf)
    this.Activities = newActivities
    await this.spinner.hide();
  }
  async scduledataall() {
    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');
      let method_id = localStorage.getItem('method');
      let method_type = localStorage.getItem('course_type');
      this.ScheduleList = [];
      if (this.IsSelfSchedule) {
        let scheduleSharedData = this.sharedDataService.getScheduleData()
        await this.ScheduleserviceService.SelfschedulesData(
          token,
          method_id,
          method_type,
          userId,
          cohort_id
        ).then(async (data) => {
          if (data[0].status == 200) {
            this.spinner.show();
            var list = JSON.parse(<string>data[0].json);
            this.selfPacedAfterApiCall(list.data)
          }
        });
        // if (scheduleSharedData && scheduleSharedData.length > 0) {
        //   this.selfPacedAfterApiCall(scheduleSharedData)
        // } else {
        //   await this.ScheduleserviceService.SelfschedulesData(
        //     token,
        //     method_id,
        //     method_type,
        //     userId,
        //     cohort_id
        //   ).then(async (data) => {
        //     if (data[0].status == 200) {
        //       this.spinner.show();
        //       var list = JSON.parse(<string>data[0].json);
        //       this.selfPacedAfterApiCall(list.data)
        //     }
        //   });
        // }
      }
    });
  }
  SelfScheduleArray() {
    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;
    });
  }
  GetCalTime() {
    this.noOfMin = 0;
    let cou = 0;
    if (this.calScheduleList && this.calScheduleList.length > 0) {
      if (!this.IsSelfSchedule) {
        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.IsSelfSchedule) {
            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;
      }
    });
  }
  monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 1 : months + 1;
  }
  GetExamCalTime() {
    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) {
      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;
  }
  async getAllComponentTime() {
    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.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;
            }
          }
        );
      }
    });
  }
  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,
    };
  }
  async getLeaderBoard() {
    let leaderBoardSharedData = this.sharedDataService.getLeaderBoardData()
    if (leaderBoardSharedData && leaderBoardSharedData.length > 0) {
      this.LeaderBoard = [];
      var i = 1;
      let user_id = localStorage.getItem('CisspUserId');
      leaderBoardSharedData.forEach((element, index, object) => {
        if (element.userid == user_id) {
          element['SRNO'] = i;
          this.CurrentPoint = element.point;
          this.ImproveAvatar = element.avatar_url;
          this.CurrentName = element.aliasname
            ? element.aliasname
            : element.NAME;
          this.CurrentRank = element.SRNO;
          this.CurrentOpt_in = element.opt_in;
          i++;
        }
        if (element.opt_in != 1 && element.userid != user_id) {
          if (element.last_login && element.last_login.length > 0) {
            element['SRNO'] = i;
            this.LeaderBoard.push(element);
            i++;
          }
        }
      });
    } else {
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = session
          let user_id = localStorage.getItem('CisspUserId');
          await this.DashboardserviceService.getLeaderborad(user_id, token).then(
            async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                var i = 1;
                this.sharedDataService.setLeaderBoardData(list.data)
                list.data.forEach((element, index, object) => {
                  if (element.userid == user_id) {
                    element['SRNO'] = i;
                    this.CurrentPoint = element.point;
                    this.ImproveAvatar = element.avatar_url;
                    this.CurrentName = element.aliasname
                      ? element.aliasname
                      : element.NAME;
                    this.CurrentRank = element.SRNO;
                    this.CurrentOpt_in = element.opt_in;
                    i++;
                  }
                  if (element.opt_in != 1 && element.userid != user_id) {
                    if (element.last_login && element.last_login.length > 0) {
                      element['SRNO'] = i;
                      this.LeaderBoard.push(element);
                      i++;
                    }
                  }
                });
              }
            }
          );
          this.spinner.hide();
        }
      });
    }
  }
  async scoreImprove() {
    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 course = localStorage.getItem('CisspCourseId');
        await this.DashboardserviceService.scoreImprove(
          userId,
          token,
          course
        ).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            if (list.data && list.data.length > 0) {
              list.data.forEach((element) => {
                if (!element['kpoint']) {
                  element['kpoint'] = 0;
                }
                element['PogressPer'] = Math.round(
                  (parseFloat(element.kpoint) * 100) /
                  parseFloat(element.kpoint_ttl)
                );
                if (!element['PogressPer']) {
                  element['PogressPer'] = 0;
                }
                if (!element['ppoint']) {
                  element['ppoint'] = 0;
                }
                element['CATPogressPer'] = Math.round(
                  (parseFloat(element.ppoint) * 100) /
                  parseFloat(element.ppoint_ttl)
                );
                if (!element['CATPogressPer']) {
                  element['CATPogressPer'] = 0;
                }
                if (!element['video_point']) {
                  element['video_point'] = 0;
                }
                element['VideoPogressPer'] = Math.round(
                  (parseFloat(element.video_point) * 100) /
                  parseFloat(element.video_point_ttl)
                );
                if (!element['VideoPogressPer']) {
                  element['VideoPogressPer'] = 0;
                }
                if (!element['flashpoint']) {
                  element['flashpoint'] = 0;
                }
                element['PracticeTestPogressPer'] = Math.round(
                  (parseFloat(element.ppoint) * 100) /
                  parseFloat(element.ppoint_ttl)
                );
                element['PracticeQuestionPogressPer'] = Math.round(
                  (parseFloat(element.pq_point) * 100) /
                  parseFloat(element.pq_point_ttl)
                );
                if (element.flashpoint > element.flashpoint_ttl) {
                  element['FlashPogressPer'] = 100;
                } else {
                  element['FlashPogressPer'] = Math.round(
                    (parseFloat(element.flashpoint) * 100) /
                    parseFloat(element.flashpoint_ttl)
                  );
                }
                if (!element['FlashPogressPer']) {
                  element['FlashPogressPer'] = 0;
                }
                if (!element['mind_point']) {
                  element['mind_point'] = 0;
                }
                element['Mindmapper'] = Math.round(
                  (parseFloat(element.mind_point) * 100) /
                  parseFloat(element.mind_point_ttl)
                );
                if (!element['Mindmapper']) {
                  element['Mindmapper'] = 0;
                }
                element['total'] =
                  element['flashpoint'] +
                  element['video_point'] +
                  element['pq_point'] +
                  element['kpoint'] +
                  element['mind_point'];
                this.ImproveTotalPoint += element['total'];
              });
              this.ScoreImprove = list.data;
            }
          }
        });
      }
    });
  }
  retuey() {
    window.location.reload();
  }
  async getScheduleDomain() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        var method_type = localStorage.getItem('course_type');
        var method_id = localStorage.getItem('method');
        this.spinner.show();
        await this.CourseserviceService.getScheduleDomain(
          method_type,
          method_id,
          token
        ).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.scheduleDomain = list.data;
            this.spinner.hide();
          } else {
            this.spinner.hide();
          }
        });
      }
    });
  }
  async getResult() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        let user_id = localStorage.getItem('CisspUserId');
        var cid = localStorage.getItem('CisspCourseId');
        var cohort_id = localStorage.getItem('cohort_id');
        this.spinner.show();
        await this.CourseserviceService.getDashboardPercentage(
          user_id,
          cid,
          cohort_id,
          token
        ).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.domainsData = list.data;
            let sum = 0;
            let i = 0;
            let w = [9, 11, 12, 12, 12, 12, 12, 12];
            this.domainsData.forEach((element) => {
              element.weight = w[i];
              i++;
              sum += element.totalPro;
            });
            localStorage.setItem(
              'domainsData',
              JSON.stringify(this.domainsData)
            );
            this.spinner.hide();
          } else {
            this.spinner.hide();
          }
        });
      }
    });
  }
  StartExam(item) {
    window.sessionStorage.setItem('main_title_id', item.title_id);
    if (item.type == 'KA') {
      var data = {
        knowass_name: item.examname,
      };
      localStorage.setItem('CisspknowAssId', item.type_id);
      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') {
      var dd = btoa(JSON.stringify(item.type_id));
      this.router.navigate([`/videolesson/${dd}`]);
    } else if (item.type == 'MindMap') {
      var dd = btoa(JSON.stringify(item.type_id));
      this.router.navigate([`/mindmaps/${dd}`]);
    } else if (item.type == 'Events') {
      this.router.navigate([`/eventrecordings/`]);
    }
  }
  OpenVideoMindmapPopup(vid, id) {
    vid['d_id'] = id;
    if (vid.type == 'video') {
      this.VideoPopup = vid;
    } else if (vid.type == 'mind') {
      this.MindmapPopup = vid;
    } else {
      this.router.navigateByUrl(vid.link);
    }
  }
  popupClose(event) {
    this.VideoPopup = false;
  }
  CloseMindmap() {
    this.openMindMap = false;
  }
  Videoclick(vid) {
    this.VideoPopup = vid;
  }
  MindmappopupClose(event) {
    this.MindmapPopup = false;
  }
}