import {
  Component,
  OnInit,
  ElementRef,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  HostListener,
} from '@angular/core';
import { AuthserviceService } from '../../authservice.service';
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { ActivatedRoute, Router, RouterStateSnapshot } from '@angular/router';
import { VideoserviceService } from '../../services/video/videoservice.service';
import * as moment from 'moment';
import { Location } from '@angular/common';
import { VgApiService } from '@videogular/ngx-videogular/core';
import { SharedDataService } from 'src/app/services/SharedData/shared-data.service';
@Component({
  selector: 'app-videolesson',
  templateUrl: './videolesson.component.html',
  styleUrls: ['./videolesson.component.scss'],
})
export class VideolessonComponent implements OnInit {
  @Input() is_popup: any;
  @Output() public onComplete = new EventEmitter<VideoComplete>();
  @Output() public onPercentUpdate = new EventEmitter<VideoComplete>();
  View_Percentage: number = 0;
  Allnotes = [];
  IsExpand = [];
  IsSubExpand = [];
  VideoLesson: any;
  VideoLink: any;
  Transcript: any;
  VideoTitle: any;
  TranscriptData = [];
  SelectedVideoId = '';
  txtVideoNotes = '';
  Istopics = [];
  Issubtopics = [];
  VideoNotes: any;
  Discussion = [];
  DiscussionTxt: any;
  userId: any;
  VideoPer = 0;
  VideoSVG: any;
  Cerficationname: any;
  Shortname: any;
  AllVideoShow = [];
  SelectedChapters = [];
  callViewUpdate: boolean = false;
  api: VgApiService;
  playback: any;
  NoVideoFound: boolean = false;
  NoVideotext: string = 'No video available';
  videoPresent: boolean = false;
  video_id: any = 0;
  is_change_certi: boolean = false;
  changeVideo: boolean = false;
  changeViewPercetage: any = 0;
  SelectedSubDomainId: any;
  autoPlay: boolean = true;
  updateVideoComplete: boolean = false;
  oneTime: boolean = false;
  oneTimePercent: any = 0;
  showControls: boolean = false;
  showSettingsPopup: boolean = false;
  showPlaybackPopup: boolean = false;
  showVideoQuality: boolean = false;
  activeSettings: boolean = false;
  playbackSpeedOptions: string[] = ['0.25', '0.5', '0.75', 'Normal', '1.25', '1.5', '1.75', '2.0'];
  selectedPlaybackSpeed: string = 'Normal';
  videoQualityOptions: string[] = []
  selectedVideoQuality: string = '1080p HD'
  selectedVideo: any;
  timer: any;

  constructor(
    public VideoserviceService: VideoserviceService,
    public EleRef: ElementRef,
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public ActiveRoute: ActivatedRoute,
    private location: Location,
    public router: Router,
    public sharedDataService: SharedDataService
  ) {
    this.service.headershow = true;
    this.service.SearchValue = true;
    var access = window.localStorage.getItem('accessitem');
    if (access) {
      var set = JSON.parse(<string>access);
      if (set) {
        this.service.access.CATaccess = set.CAT_access ? true : false;
        this.service.access.Knowaccess = set.KA_access ? true : false;
        this.service.access.Practiceaccess = set.PT_access ? true : false;
        this.service.access.livechat_access = set.livechat_access
          ? true
          : false;
      }
    }

    this.userId = localStorage.getItem('CisspUserId');
    this.VideoSVG = '0 100';
  }
  @ViewChild('videoElement') videoElement!: ElementRef;
  @HostListener('document:click', ['$event'])
  onDocumentClick(event: Event): void {
    if (!this.videoElement?.nativeElement.contains(event.target)) {
      if (((!this.showPlaybackPopup && this.showVideoQuality) || (this.showPlaybackPopup && !this.showVideoQuality))) {
        this.toggleSettings();
      } else if (this.showSettingsPopup) {
        this.toggleSettings();
      }
    }
  }

  async ngOnInit() {
    let autoPlay = window.localStorage.getItem('autoPlay');
    if (autoPlay) {
      this.autoPlay = autoPlay == 'true' ? true : false;
    } else {
      this.autoPlay = true;
    }
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.spinner.hide();
    }
    try {
      this.service.title = '';
      this.ActiveRoute.params.subscribe(async (params) => {
        try {
          this.video_id = JSON.parse(atob(params['id']));
        } catch (error) { }
      });
      await this.getAllVideoLesson();
    } catch {
      this.spinner.hide();
    }
    var myVideo = document.getElementById('singleVideo') as HTMLVideoElement;
    if (myVideo.addEventListener) {
      myVideo.addEventListener(
        'contextmenu',
        function (e) {
          e.preventDefault();
        },
        false
      );
    }
  }
  changeAutoPlay() {
    this.autoPlay = !this.autoPlay;
    window.localStorage.setItem('autoPlay', this.autoPlay + '');
  }

  toggleSettings() {
    if (!this.showSettingsPopup && (this.showPlaybackPopup || this.showVideoQuality)) {
      this.showSettingsPopup = false;
      this.showPlaybackPopup = false;
      this.showVideoQuality = false;
    } else {
      this.showSettingsPopup = !this.showSettingsPopup;
    }
    this.activeSettings = !this.activeSettings;
  }
  showoption(selectedOption: any) {
    if (selectedOption == 'PlaybackOptions') {
      setTimeout(() => {
        this.showPlaybackPopup = true;
      }, 10);
      this.showSettingsPopup = false;
    } else if (selectedOption == 'QualityOptions') {
      setTimeout(() => {
        this.showVideoQuality = true;
      }, 10);
      this.showSettingsPopup = false;
    }
  }
  backShowoption(selectedOption: any) {
    if (selectedOption == 'PlaybackOptions') {
      this.showPlaybackPopup = false;
      setTimeout(() => {
        this.showSettingsPopup = true;
      }, 10);
    } else if (selectedOption == 'QualityOptions') {
      this.showVideoQuality = false;
      setTimeout(() => {
        this.showSettingsPopup = true;
      }, 10);
    }
  }
  setPlaybackSpeed(speed: string) {
    this.api.playbackRate = speed == 'Normal' ? '1.0' : speed;
    this.selectedPlaybackSpeed = speed;
  }
  async setVideoQuality(quality: string) {
    this.selectedVideoQuality = quality;
    var audi = document.getElementsByTagName('video');
    var currentTime = audi[0].currentTime
    await this.loadVideo(this.selectedVideo)
    setTimeout(() => {
      var vid = document.getElementsByTagName('video');
      vid[0].currentTime = currentTime
    }, 1000);
  }

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

  hideControls() {
    this.showControls = false;
  }
  async back() {
    let percent = this.View_Percentage
    let id = this.SelectedVideoId
    let emiter = {
      id: parseInt(id),
      percent: percent
    }
    await this.updateVideoPercentage();
    if (this.is_popup != undefined) {
      this.is_popup = false;
      this.onComplete.emit(emiter);
    } else {
      await this.location.back();
    }
  }
  async afterGetAllVideoLesson(list: any) {
    this.sharedDataService.setVideoLessonData(list);
    if (list.data.Domains && list.data.Domains.length > 0) {
      await list.data.Domains.forEach(async (element, maini) => {
        var TotalVideo = 0;
        var TotalView = 0;
        if (element.SubDomains && element.SubDomains.length > 0) {
          await element.SubDomains.forEach((elementsub, subi) => {
            if (elementsub.Videos && elementsub.Videos.length > 0) {
              this.AllVideoShow.push(elementsub.Videos);
              TotalVideo += elementsub.Videos.length;
              var ViewVideo = elementsub.Videos.filter(
                (item) => item.viewed == true
              );
              TotalView += ViewVideo.length;
              if (elementsub.Videos.length == ViewVideo.length) {
                elementsub['SubCheck'] = true;
              } else {
                elementsub['SubCheck'] = false;
              }
            } else {
              element['ViewVideo'] = 0;
              element['TotalVideo'] = 0;
            }
            var set = 0;
            this.ActiveRoute.params.subscribe(async (params) => {
              try {
                set = JSON.parse(atob(params['id']));
                this.NoVideotext =
                  'No video available in this selected cohort';
              } catch (error) { }
            });
            var videodata = elementsub.Videos.filter(
              (x) => x.id == set
            );
            if (videodata && videodata.length > 0) {
              this.videoPresent = true;
              this.loadVideo(videodata[0]);
              setTimeout(() => {
                this.topics(videodata[0].dom);
                this.subtopics(videodata[0].sdom);
              }, 100);
            }
            if (this.is_popup != undefined) {
              if (!this.is_popup.sd_id && !this.is_popup.d_id) {
                var videodata = elementsub.Videos.filter(
                  (x) => x.id == this.is_popup.id
                );

                if (videodata && videodata.length > 0) {

                  this.loadVideo(videodata[0]);
                  setTimeout(() => {
                    this.topics(videodata[0].dom);
                    this.subtopics(videodata[0].sdom);
                  }, 100);
                }
              }
            }
            if (this.is_popup != undefined) {
              if (this.is_popup.sd_id) {
                var videodata = elementsub.Videos.filter(
                  (x) =>
                    x.id == this.is_popup.id &&
                    elementsub.id == this.is_popup.sd_id
                );

                if (videodata && videodata.length > 0) {

                  this.loadVideo(videodata[0]);
                  setTimeout(() => {
                    this.topics(videodata[0].dom);
                    this.subtopics(videodata[0].sdom);
                  }, 100);
                }
              }
            }

            if (this.is_popup != undefined) {
              if (this.is_popup.d_id) {
                if (element.id == this.is_popup.d_id && subi == 0) {
                  var videodata = elementsub.Videos;
                  if (videodata && videodata.length > 0) {

                    this.loadVideo(videodata[0]);
                    setTimeout(() => {
                      this.topics(videodata[0].dom);
                      this.subtopics(videodata[0].sdom);
                    }, 100);
                  }
                }
              }
            }
            if (this.is_popup == undefined && set == 0) {
              if (maini == 0 && subi == 0) {
                var videodata = elementsub.Videos;
                if (videodata && videodata.length > 0) {
                  this.loadVideo(videodata[0]);
                  setTimeout(() => {
                    this.topics(videodata[0].dom);
                    this.subtopics(videodata[0].sdom);
                  }, 100);
                }
              }
            }
          });
        } else {
          element['ViewVideo'] = 0;
          element['TotalVideo'] = 0;
        }
        if (
          TotalView != 0 &&
          TotalVideo != 0 &&
          TotalView == TotalVideo
        ) {
          element['DomainCheck'] = true;
        } else {
          element['DomainCheck'] = false;
        }
        element['ViewVideo'] = TotalView;
        element['TotalVideo'] = TotalVideo;
      });
    }
    this.VideoLesson = list.data.Domains;
    if (this.VideoLesson && this.VideoLesson.length > 0) {
      var TotView = 0;
      var TotalVideosdata = 0;

      await this.VideoLesson.forEach((element, i) => {
        TotView += element['ViewVideo'];
        TotalVideosdata += element['TotalVideo'];
        element.SubDomains.forEach((sd, j) => {
          sd.Videos.forEach((v) => {
            v['dom'] = i;
            v['sdom'] = j;
          });
        });
      });
      this.VideoPer = Math.round((TotView * 100) / TotalVideosdata);
      this.VideoPer = this.VideoPer ? this.VideoPer : 0;
      this.VideoSVG = this.VideoPer + ' ' + (100 - this.VideoPer);
    }
    if (list.data.Certificates && list.data.Certificates.length > 0) {
      this.Cerficationname = list.data.Certificates[0].certificate_name;
      this.Shortname = list.data.Certificates[0].short_name;
    }

    if (this.is_popup == undefined && !this.videoPresent) {
      var set = 0;
      this.ActiveRoute.params.subscribe(async (params) => {
        try {
          if (params['id']) this.service.ShowError(this.NoVideotext);
        } catch (error) { }
      });
      this.videoPresent = false;
    }
  }
  async getAllVideoLesson() {
    const snapshot: RouterStateSnapshot = this.router.routerState.snapshot;
    if (!localStorage.getItem('CisspCourseId')) {
      this.router.navigate(['enrolledcourse'], {
        queryParams: { returnUrl: snapshot.url },
      });
      return;
    }
    this.AllVideoShow = [];
    let videoData = this.sharedDataService.getVideoLessonData()
    if (Object.keys(videoData).length > 0) {
      this.afterGetAllVideoLesson(videoData)
    } else {
      this.spinner.show();

      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = session
          let ids = '';
          if (localStorage.getItem('method') != '0' && localStorage.getItem('method') != null) {
            let method = localStorage.getItem('method');
            let course_type = localStorage.getItem('course_type');
            await this.service
              .getMembershipMaterials(method, course_type, 'Video', token)
              .then(async (data) => {
                var list = JSON.parse(<string>data[0].json);
                list.data.forEach((element) => {
                  ids += element.material_id + ',';
                });
              });
          }
          if (ids.endsWith(',') == true) {
            ids = ids.substring(0, ids.length - 1);
          }
          var userId = localStorage.getItem('CisspUserId');
          let c_id;
          if (localStorage.getItem('CisspCourseId') != null) {
            c_id = localStorage.getItem('CisspCourseId');
          } else {
            this.router.navigate(['/enrolledcourse']);
          }

          await this.VideoserviceService.GetAllVideoLesson(
            token,
            userId,
            c_id,
            ids,
            this.video_id
          ).then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              this.afterGetAllVideoLesson(list);
            }
          });
          this.spinner.hide();
        }
      });
    }
  }
  topics(j) {
    this.IsSubExpand = [];
    if (this.IsExpand[j] == true) {
      this.IsExpand[j] = false;
    } else {
      this.IsExpand = [];
      this.IsExpand[j] = true;
    }
    if (this.Istopics[j] == true) {
      this.Istopics[j] = false;
      this.Issubtopics = [];
    } else {
      this.Istopics = [];
      this.Istopics[j] = true;
    }
  }
  subtopics(j) {
    if (this.IsSubExpand[j] == true) {
      this.IsSubExpand[j] = false;
    } else {
      this.IsSubExpand = [];
      this.IsSubExpand[j] = true;
    }
    if (this.Issubtopics[j] == true) {
      this.Issubtopics[j] = false;
    } else {
      this.Issubtopics = [];
      this.Issubtopics[j] = true;
    }
  }
  mobileClose() {
    if (window.innerWidth <= 768) {
      const player = this.EleRef.nativeElement.querySelector('video');
      player.pause();
      document.getElementById('mobile').style.display = 'none';
    }
  }
  async loadVideo(item) {
    this.selectedVideo = item;
    this.oneTimePercent = item.view_percent;
    this.oneTime = false;
    this.updateVideoComplete = false;
    if (window.innerWidth <= 768) {
      document.getElementById('mobile').style.display = 'block';
    }
    if (!item.is_change_certi) {
      this.is_change_certi = item.is_change_certi;
    }
    this.View_Percentage = 0;
    this.SelectedVideoId = '';
    this.SelectedVideoId = item.id;
    if (this.SelectedVideoId != '') {
      this.callViewUpdate = true;
      this.changeViewPercetage = 0;
    }

    this.VideoLink = '';
    this.Transcript = '';
    this.TranscriptData = [];
    if (this.selectedVideoQuality == '720p' && item.video_lesson_link_720p) {
      this.VideoLink = item.video_lesson_link_720p;
    } else if (this.selectedVideoQuality == '480p' && item.video_lesson_link_480p) {
      this.VideoLink = item.video_lesson_link_480p;
    } else if (this.selectedVideoQuality == '360p' && item.video_lesson_link_360p) {
      this.VideoLink = item.video_lesson_link_360p;
    } else if (this.selectedVideoQuality == '240p' && item.video_lesson_link_240p) {
      this.VideoLink = item.video_lesson_link_240p;
    } else if (this.selectedVideoQuality == '144p' && item.video_lesson_link_144p) {
      this.VideoLink = item.video_lesson_link_144p;
    } else {
      this.VideoLink = item.video_link
    }
    this.videoQualityOptions = [];
    if (item.video_link) { this.videoQualityOptions.push('1080p HD') }
    if (item.video_lesson_link_720p) { this.videoQualityOptions.push('720p') }
    if (item.video_lesson_link_480p) { this.videoQualityOptions.push('480p') }
    if (item.video_lesson_link_360p) { this.videoQualityOptions.push('360p') }
    if (item.video_lesson_link_240p) { this.videoQualityOptions.push('240p') }
    if (item.video_lesson_link_144p) { this.videoQualityOptions.push('144p') }
    this.VideoTitle = item.video_title;
    this.SelectedChapters = item.chapters;
    this.SelectedSubDomainId = item.sd_id;
    let me = this;
    this.SelectedChapters.forEach((element, i) => {
      element['vid'] = item.id;
      i == 0 ? (element['active'] = true) : (element['active'] = false);
    });
    if (item.transcript_link) {
      this.TranscriptData = JSON.parse(item.transcript_link);
      this.TranscriptData.forEach((element) => {
        element.FromTime = moment(element.FromTime, 'mm:ss').diff(
          moment().startOf('day'),
          'seconds'
        );
        element.ToTime = moment(element.ToTime, 'mm:ss').diff(
          moment().startOf('day'),
          'seconds'
        );
      });
    }
    this.Allnotes = [];
    this.VideoNotes = [];
    this.txtVideoNotes = '';

    await this.getVideoNotesByUserOnChangeVideo(item.id);
    await this.GetVideoDiscussion();
    var player = this.EleRef.nativeElement.querySelector('video');
    player.load();
    this.api.playbackRate = this.playback;

    player.addEventListener('timeupdate', () => {
      var audi = document.getElementsByTagName('video');
      if (audi[0]?.duration.toString() != 'NaN') {
        if (!me.oneTime && this.oneTimePercent < 100) {
          audi[0].currentTime =
            (parseInt(this.oneTimePercent) / 100) * audi[0]?.duration;
          me.oneTime = true;
        }
        let currentTime = audi[0]?.currentTime;
        let duration = audi[0]?.duration;

        if (!me.updateVideoComplete) {
          if (duration - currentTime != 0 && duration - currentTime <= 30) {
            me.updateVideoComplete = true;
            me.saveVideoPercentage();
          }
        }
        var span = document.getElementsByClassName('transcript');
        for (let i = 0; i < span.length; i++) {
          var time = Number(span[i].getAttribute('id'));
          if (time < audi[0].currentTime) {
            if (i > 0) {
              span[i - 1].setAttribute('style', 'background:#0000');
            }
            span[i].setAttribute('style', 'background:#DF166A;color:#fff');
          }
        }
      }
    });

    player.addEventListener('timeupdate', async () => {
      var audi = document.getElementsByTagName('video');
      if (audi[0]?.duration.toString() != 'NaN') {
        if (me.View_Percentage != 0 && me.callViewUpdate) {
          me.callViewUpdate = false;
          me.changeVideo = true;
          if (this.View_Percentage != 100) {
            me.View_Percentage = (audi[0].currentTime / audi[0].duration) * 100;
            me.SelectedChapters.forEach((chapt) => {
              var hms = chapt.FromTime;
              var a = hms.split(':');
              var seconds = parseInt(a[0]) * 60 + parseInt(a[1]);
              if (seconds < audi[0].currentTime) {
                me.SelectedChapters.forEach((c) => {
                  c.active = false;
                  c.progress = false;
                });
                chapt.done = true;
                chapt.progress = true;
                chapt.active = true;
              }
            });
          }
          await me.updateVideoPercentage();
        } else {
          if (audi.length > 0) {
            if (me.changeVideo && me.changeViewPercetage != 100) {
              me.changeVideo = false;
            }
            me.View_Percentage = (audi[0].currentTime / audi[0].duration) * 100;

            me.SelectedChapters.forEach((chapt) => {
              var hms = chapt.FromTime;
              var a = hms.split(':');
              var seconds = parseInt(a[0]) * 60 + parseInt(a[1]);
              if (seconds < audi[0].currentTime) {
                me.SelectedChapters.forEach((c) => {
                  c.active = false;
                  c.progress = false;
                });
                chapt.done = true;
                chapt.progress = true;
                chapt.active = true;
              }
            });
          }
        }
      }
    });
    setTimeout(() => {
      this.VideoLesson.forEach((element) => {
        element.SubDomains.forEach((sd) => {
          sd.Videos.forEach((v) => {
            v.active = false;
          });
        });
      });
      item['active'] = true;
    }, 200);
  }
  changeChapters(chapt) {
    this.SelectedChapters.forEach((element) => {
      if (element['active'] == true) {
        element['done'] = true;
      }
      element['active'] = false;
    });
    chapt['active'] = true;
    var hms = chapt.FromTime;
    var a = hms.split(':');
    var seconds = parseInt(a[0]) * 60 + parseInt(a[1]);
    const video = document.getElementsByTagName('video');
    video[0].currentTime = seconds;
  }
  transcriptClick(item) {
    const video = document.getElementsByTagName('video');
    video[0].currentTime = item.FromTime;
    var span = document.getElementsByClassName('transcript');
    for (let i = 0; i < span.length; i++) {
      span[i].setAttribute('style', 'background:#0000');
    }
  }
  async saveVideoPercentage() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        let c_id;
        if (localStorage.getItem('CisspCourseId') != null) {
          c_id = localStorage.getItem('CisspCourseId');
        } else {
          this.router.navigate(['/enrolledcourse']);
        }
        var userIdset = localStorage.getItem('CisspUserId');
        var cohort_id = localStorage.getItem('cohort_id');
        var data = {
          type_id: this.SelectedVideoId,
          user_id: userIdset,
          cohort_id: cohort_id,
          type: 'VIDEO',
          view_percent: 100,
          is_completed: 1,
        };
        await this.VideoserviceService.VideoUpdate(token, data);
        this.View_Percentage = 0;
      }
    });
  }
  chaptersEvent(event, chapters) {
    const audi = document.getElementsByTagName('video');
  }

  async saveVideoNotes() {
    var userId = localStorage.getItem('CisspUserId');
    if (
      this.txtVideoNotes == '' ||
      this.txtVideoNotes == undefined ||
      this.txtVideoNotes == null
    ) {
    } else {
      await this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            var token = session
            await this.VideoserviceService.VideoNoteAdd(
              userId,
              this.SelectedVideoId,
              this.txtVideoNotes,
              'VIDEO',
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.getVideoNotesByUser();
              }
            });
          }
        });
    }
  }
  async getVideoNotesByUserOnChangeVideo(id) {
    this.Allnotes = [];
    this.VideoNotes = [];
    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');
        await this.VideoserviceService.GetVideoNotesByUser(
          userId,
          id,
          'VIDEO',
          token
        ).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            if (list.data.length > 0) {
              this.VideoNotes = list.data;
              this.Allnotes = this.VideoNotes;
              this.Allnotes.forEach((element) => {
                this.txtVideoNotes = element.notes;
              });
            }
          }
        });
        this.spinner.hide();
      }
    });
  }
  async getVideoNotesByUser() {
    this.Allnotes = [];
    this.VideoNotes = [];
    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');
        await this.VideoserviceService.GetVideoNotesByUser(
          userId,
          this.SelectedVideoId,
          'VIDEO',
          token
        ).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            if (list.data.length > 0) {
              this.VideoNotes = list.data;
              this.Allnotes = this.VideoNotes;
              this.Allnotes.forEach((element) => {
                this.txtVideoNotes = element.notes;
              });
            }
          }
        });
        this.spinner.hide();
      }
    });
  }
  async addDiscussion() {
    if (
      this.DiscussionTxt == '' ||
      this.DiscussionTxt == null ||
      this.DiscussionTxt == undefined
    ) {
      this.service.ShowError('Please enter discussion');
    } else {
      this.spinner.show();
      await this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            var token = session
            var userId = localStorage.getItem('CisspUserId');
            this.spinner.show();

            await this.VideoserviceService.AddVideoDiscussion(
              userId,
              0,
              this.SelectedVideoId,
              this.DiscussionTxt,
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.DiscussionTxt = '';
                await this.GetVideoDiscussion();
                this.service.ShowSuccess('Discussion successfully post');
              }
            });
            this.spinner.hide();
          }
        });
    }
  }
  async GetVideoDiscussion() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        this.spinner.show();
        await this.VideoserviceService.GetVideoDiscussion(
          this.SelectedVideoId,
          token
        ).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.Discussion = list.data;
            if (this.Discussion.length > 0) {
              this.Discussion.forEach((element) => {
                let invDate = new Date(element.createdAt);
                let invDate1 = invDate.toString().substring(4, 15);
                element.createdAt = invDate1;
              });
            }
          }
        });
        this.spinner.hide();
      }
    });
  }
  async chnagemark() {
    if (this.VideoLesson && this.VideoLesson.length > 0) {
      await this.VideoLesson.forEach(async (element) => {
        var TotalVideo = 0;
        var TotalView = 0;
        if (element.SubDomains && element.SubDomains.length > 0) {
          await element.SubDomains.forEach((elementsub) => {
            if (elementsub.Videos && elementsub.Videos.length > 0) {
              this.AllVideoShow.push(elementsub.Videos);
              TotalVideo += elementsub.Videos.length;
              var ViewVideo = elementsub.Videos.filter(
                (item) => item.viewed == true
              );
              TotalView += ViewVideo.length;
              if (elementsub.Videos.length == ViewVideo.length) {
                elementsub['SubCheck'] = true;
              } else {
                elementsub['SubCheck'] = false;
              }
            } else {
              element['ViewVideo'] = 0;
              element['TotalVideo'] = 0;
            }
          });
        } else {
          element['ViewVideo'] = 0;
          element['TotalVideo'] = 0;
        }
        if (TotalView != 0 && TotalVideo != 0 && TotalView == TotalVideo) {
          element['DomainCheck'] = true;
        } else {
          element['DomainCheck'] = false;
        }
        element['ViewVideo'] = TotalView;
        element['TotalVideo'] = TotalVideo;
      });
    }
  }
  async vidEnded() {
    if (this.autoPlay) {
      if (!this.is_change_certi) {
        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');
              let c_id;
              if (localStorage.getItem('CisspCourseId') != null) {
                c_id = localStorage.getItem('CisspCourseId');
              } else {
                this.router.navigate(['/enrolledcourse']);
              }
              var userIdset = localStorage.getItem('CisspUserId');
              var cohort_id = localStorage.getItem('cohort_id');
              var data = {
                type_id: this.SelectedVideoId,
                user_id: userIdset,
                cohort_id: cohort_id,
                type: 'VIDEO',
                view_percent: 100,
                is_completed: 1,
              };
              let emiter = {
                id: parseInt(this.SelectedVideoId),
                percent: 100
              }
              this.onPercentUpdate.emit(emiter)
              await this.VideoserviceService.VideoUpdate(token, data);
              this.View_Percentage = 0;
            }
          });
        let loaded = 0;
        await this.VideoLesson.forEach(async (element, i) => {
          await element.SubDomains.forEach(async (sd, j) => {
            await sd.Videos.forEach(async (v, k) => {
              if (v.id == this.SelectedVideoId && loaded == 0 && v.active) {
                v.viewed = true;
                if (k + 1 == sd.Videos.length) {
                  loaded = 1;
                  if (j + 1 == element.SubDomains.length) {
                    await this.loadVideo(
                      this.VideoLesson[i + 1].SubDomains[0].Videos[0]
                    );
                    setTimeout(async () => {
                      await this.topics(
                        this.VideoLesson[i + 1].SubDomains[0].Videos[0].dom
                      );
                      await this.subtopics(
                        this.VideoLesson[i + 1].SubDomains[0].Videos[0].sdom
                      );
                    }, 100);
                  } else {
                    if (element.SubDomains[j + 1].Videos[0].viewed) {
                      await this.loadVideo(
                        element.SubDomains[j + 1].Videos[k + 1]
                      );
                      setTimeout(async () => {
                        await this.subtopics(
                          element.SubDomains[j + 1].Videos[k + 1].sdom
                        );
                      }, 100);
                    } else {
                      await this.loadVideo(element.SubDomains[j + 1].Videos[0]);
                      setTimeout(async () => {
                        await this.subtopics(
                          element.SubDomains[j + 1].Videos[0].sdom
                        );
                      }, 100);
                    }
                  }
                } else {
                  loaded = 1;
                  await this.loadVideo(sd.Videos[k + 1]);
                }
              }
            });
          });
        });
        await this.chnagemark();
      }
    }
  }
  async updateVideoPercentage() {
    if (!this.is_change_certi) {
      var user_id = localStorage.getItem('CisspUserId');
      var cohort_id = localStorage.getItem('cohort_id');
      var data = {
        type_id: this.SelectedVideoId,
        user_id: user_id,
        cohort_id: cohort_id,
        type: 'VIDEO',
        view_percent: this.View_Percentage,
        is_completed: this.View_Percentage == 100 ? 1 : 0,
      };
      let emiter = {
        id: parseInt(this.SelectedVideoId),
        percent: this.View_Percentage
      }
      this.onPercentUpdate.emit(emiter)
      await this.auth.getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            var token = session
            await this.VideoserviceService.VideoUpdate(token, data).then(
              (res) => {
                var list = JSON.parse(<string>res[0].json);

                if (list.data.length > 0) {
                  this.View_Percentage = list.data[0].view_percent
                    ? list.data[0].view_percent
                    : 0;
                  if (this.SelectedVideoId == '') {
                    this.changeViewPercetage = list.data[0].view_percent
                      ? list.data[0].view_percent
                      : 0;
                    this.callViewUpdate = true;
                  }
                } else {
                  this.View_Percentage = 0;
                }
              }
            );
          }
        });
    }
  }
  onPlayerReady(api: VgApiService) {
    this.api = api;
    this.playback = this.api.playbackRate;
    let me = this
    document.onkeydown = function (event) {
      const video = document.getElementsByTagName('video');
      const activeElement = document.activeElement;
      const isInputFocused = activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA';
      if (isInputFocused) {
        return; // Ignore keycodes if input is focused
      }
      switch (event.keyCode) {
        case 37://ArrowLeft-  Backward 10 sec
          video[0].currentTime = video[0].currentTime - 10;
          break;
        case 38://ArrowUp- volume increase
          if (video[0].volume != 1)
            video[0].volume += 0.1;
          break;
        case 39://ArrowRight- Forward 10 sec
          video[0].currentTime = video[0].currentTime + 10;
          break;
        case 40://ArrowDown- Volume decrease
          if (video[0].volume > 0.1)
            video[0].volume -= 0.1;
          break;
        case 32://SpaceBar- Play Pause
          event.preventDefault();
          video[0].paused ? video[0].play() : video[0].pause();
          break;
        case 70://F- Fullscreen
          me.api.fsAPI.toggleFullscreen()
          break;
        case 74://J- Backward 10 sec
          video[0].currentTime = video[0].currentTime - 10;
          break;
        case 75://K- Play Paused
          video[0].paused ? video[0].play() : video[0].pause();
          break;
        case 76://L- Forward 10 sec
          video[0].currentTime = video[0].currentTime + 10;
          break;
        case 77://M- Mute Unmute
          video[0].volume = video[0].volume == 1 ? 0 : 1;
          break;
        case 188://>- Slod down video playback rate
          if (video[0].playbackRate > 0.25)
            video[0].playbackRate -= 0.25
          me.playbackRate(video[0].playbackRate)
          break;
        case 190://>- Speedup video playback rate
          video[0].playbackRate += 0.25
          me.playbackRate(video[0].playbackRate)
          break;

      }
    };
  }
  playbackRate(item) {
    this.selectedPlaybackSpeed = item == 1 ? "Normal" : item;
  }
  changeplay() {
    if (this.api.state == 'paused') this.api.play();
    if (this.api.state == 'playing') this.api.pause();
  }
  ngAfterViewChecked() {
    this.playback = this.api.playbackRate;
  }
  onFocusOutEvent(event) {
    this.saveVideoNotes();
  }
  forwordvideo() {
    const video = document.getElementsByTagName('video');
    video[0].currentTime = video[0].currentTime + 10;
  }
  backwordvideo() {
    const video = document.getElementsByTagName('video');
    video[0].currentTime = video[0].currentTime - 10;
  }
}
export interface VideoComplete {
  id: number;
  percent: number;
}
