import { ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, Input, OnInit, Output, ViewChild } from '@angular/core';
import { MindmapService } from 'src/app/services/mindmap/mindmap.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { AuthserviceService } from '../../authservice.service';
import { ServicesService } from '../../services.service';
import { Router, ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import { Location } from '@angular/common';
import { VgApiService } from '@videogular/ngx-videogular/core';
import { VideoserviceService } from 'src/app/services/video/videoservice.service';
import { SharedDataService } from 'src/app/services/SharedData/shared-data.service';

@Component({
  selector: 'app-mindmaps',
  templateUrl: './mindmaps.component.html',
  styleUrls: ['./mindmaps.component.scss'],
})
export class MindmapsComponent implements OnInit {
  @Input() is_popup: any;
  @Output() public onComplete = new EventEmitter<VideoComplete>();
  @Output() public onPercentUpdate = new EventEmitter<VideoComplete>();

  View_Percentage: number = 0;
  callViewUpdate: boolean = false;
  Allnotes = [];
  VideoNotes = [];
  showSubdomain = [];
  showImages = [];
  showVideos = [];
  showImages1: boolean = false;
  showVideos1: boolean = false;
  MindMaplistdata = [];
  MindMapdesc = '';
  VideoLink = '';
  explantion = '';
  VideoLinkS = '';
  VideoTitle = '';
  TranscriptData = [];
  Discussion = [];
  txtVideoNotes = '';
  DiscussionTxt = '';
  StudyMaterials = [];
  Flashcards = [];
  userid: any;
  References = [];
  Video = [];
  DiscussionText = '';
  Mindid = '';
  minmapname = '';
  SelectedChapters = [];
  api: VgApiService;
  playback: any;
  NoVideoFound: boolean = false;
  NoVideotext: string = "No mindmaps available";
  MindMapPresent: boolean = false;
  autoPlay: boolean = true;
  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 EleRef: ElementRef,
    public MindmapService: MindmapService,
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    private location: Location,
    public router: Router,
    public ActiveRoute: ActivatedRoute,
    private cdRef: ChangeDetectorRef,
    public VideoserviceService: VideoserviceService,
    public sharedDataService: SharedDataService
  ) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
    this.ActiveRoute.params.subscribe(async (params) => {
      try {
        var set = JSON.parse(atob(params['id']));
      } catch (error) {
      }
    });
  }
  back() {
    let percent = this.View_Percentage
    let id = this.Mindid
    let emiter = {
      id: parseInt(id),
      percent: percent
    }
    if (this.is_popup != undefined) {
      this.is_popup = false;
      this.onComplete.emit(emiter);
    }
    else {
      this.location.back();
    }
  }
  @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();
      }
    }
  }
  ngOnInit(): void {
    this.userid = localStorage.getItem('CisspUserId');
    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.Mindmaplist();
    var myVideo = document.getElementById("singleVideo") as HTMLVideoElement;
    if (myVideo?.addEventListener) {
      myVideo.addEventListener('contextmenu', function (e) {
        e.preventDefault();
      }, false);
    }

    let autoPlay = window.localStorage.getItem('autoPlay');
    if (autoPlay) {
      this.autoPlay = autoPlay == 'true' ? true : false;
    } else {
      this.autoPlay = true;
    }
  }

  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;
  }
  Videoclick(vid) {
    var data = btoa(JSON.stringify(vid.id));
    this.router.navigate([`/videolesson/${data}`]);
  }
  expandDomain(i) {
    this.showSubdomain[i] = !this.showSubdomain[i];
    this.MindMapdesc = '';
    this.explantion = '';
    this.StudyMaterials = [];
    this.Discussion = [];
    this.Video = [];
    this.showImages = [];
    this.showVideos = [];
    this.showImages1 = false;
    this.showVideos1 = false;
    this.showSubdomain.forEach((data, index) => {
      if (i != index) {
        this.showSubdomain[index] = false
      }
    })
  }
  expandImage(item, j) {
    this.Mindid = '';
    this.Mindid = item.id;
    this.MindMapdesc = '';
    this.explantion = '';
    this.StudyMaterials = [];
    this.Discussion = [];
    this.Video = [];
    this.Video = item.Video;
    this.Video.forEach(data => {
      data['topic_list'] = JSON.parse(
        data.topic_list
      )
        ? JSON.parse(data.topic_list)
        : [];
    })
    this.Discussion = item.Discussion;
    this.minmapname = '';
    this.minmapname = item.name;

    this.StudyMaterials = item.StudyMaterials;
    this.MindMapdesc = item.description;
    this.Flashcards = [];
    this.Flashcards = item.Flashcards;
    this.References = [];
    this.References = item.References;
    this.SelectedChapters = item.chapters;

    this.showImages = [];
    this.showVideos = [];
    this.showImages[j] = true;
    this.showVideos[j] = false;
    this.showImages1 = true;
    this.showVideos1 = false;
  }
  expandVideo(item, j) {
    this.minmapname = '';
    this.minmapname = item.name;
    this.Mindid = '';
    this.Mindid = item.id;
    this.VideoTitle = item.name;
    this.showImages = [];
    this.showVideos = [];
    this.showImages[j] = false;
    this.showVideos[j] = true;
    this.showImages1 = false;
    this.showVideos1 = true;
    this.loadVideo(item);
  }
  async afterMindMapsApiCall(list: any) {
    this.MindMaplistdata = list;
    this.sharedDataService.setMindMapsData(list)
    if (this.MindMaplistdata.length > 0) {
      var set = 0; var Arraycount = 0;
      this.ActiveRoute.params.subscribe(async (params) => {
        try {
          set = JSON.parse(atob(params['id']));
          this.NoVideotext = "No mindmaps available in this selected cohort";
        } catch (error) { }
      });
      this.MindMaplistdata.forEach((element, MinmapIndex) => {

        if (element.MindMaps) {
          var dataset: any = element.MindMaps.filter(
            (x) => x.id == set
          );
          if (dataset.length > 0) {
            this.expandDomain(Arraycount)
            this.expandVideo(dataset[0], 0);
            this.MindMapPresent = true;
            return;
          }
          if (this.is_popup != undefined) {
            var dataset: any = element.MindMaps.filter(
              (x) => x.id == this.is_popup.id
            );
            let ind = 0
            element.MindMaps.forEach((el,i) => {
              if(el.id==this.is_popup.id){
                ind=i
              }
            });
            if (dataset.length > 0) {
              this.expandDomain(Arraycount)
              this.expandVideo(dataset[0], ind);
              return;
            }
          }
          if (this.is_popup != undefined) {
            if (this.is_popup.d_id) {
              if (element.id == this.is_popup.d_id) {
                var dataset: any = element.MindMaps
                if (dataset.length > 0) {
                  this.expandDomain(Arraycount)
                  this.expandVideo(dataset[0], 0);
                  return;
                }
              }
            }
          }
          if (this.is_popup == undefined && set == 0) {
            if (MinmapIndex == 0) {
              var dataset: any = element.MindMaps
              if (dataset.length > 0) {
                this.expandDomain(Arraycount)
                this.expandVideo(dataset[0], 0);
                return;
              }
            }
          }
        }
        Arraycount = Arraycount + 1;
      });
      if (this.is_popup == undefined && !this.MindMapPresent) {
        var set = 0;
        this.ActiveRoute.params.subscribe(async (params) => {
          try {
            if (params['id'])
              this.service.ShowError(this.NoVideotext);
          } catch (error) { }
        });
        this.MindMapPresent = false;
      }
    }
    this.changemark();
  }
  async Mindmaplist() {
    let mindData = this.sharedDataService.getMindMapsData()
    if (mindData.length > 0) {
      this.afterMindMapsApiCall(mindData)
    } 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") {
            let method = localStorage.getItem('method');
            let course_type = localStorage.getItem('course_type');
            await this.service.getMembershipMaterials(method, course_type, "Mindmap", 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);
          }
          await this.MindmapService.MindMapList(token, ids).then(
            async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.afterMindMapsApiCall(list.data)
                await this.spinner.hide();
              } else {
                await this.spinner.hide();
              }
            },
            (err) => {
              this.spinner.hide();
            }
          );
        }
      });
    }
  }
  addDiscussion() { }
  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.Mindid,
              this.txtVideoNotes,
              "MIND",
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.getVideoNotesByUser();
                this.txtVideoNotes = '';
              }
            });
          }
        });
    }
  }
  async vidEnded() {
    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(['/sidenav/selectcourse']);
        }

        var userIdset = localStorage.getItem('CisspUserId');
        var cohort_id = localStorage.getItem('cohort_id');
        var data = {
          type_id: this.Mindid,
          user_id: userIdset,
          cohort_id: cohort_id,
          type: 'MIND',
          view_percent: 100,
          is_completed: 1
        };
        let emiter = {
          id: parseInt(this.Mindid),
          percent: 100
        }
        this.onPercentUpdate.emit(emiter)
        await this.MindmapService.VideoUpdate(token, data);
        this.View_Percentage = 0;
      }
    });
    this.MindMaplistdata.forEach(element => {
      element.MindMaps.forEach(el => {
        if (el.id == this.Mindid) {
          el.viewed = true;
        }
      });
    });
    let loaded = 0;
    if(this.autoPlay){
      await this.MindMaplistdata.forEach(async (element, i) => {
        await element.MindMaps.forEach(async (v, k) => {
          if (v.id == this.Mindid && loaded == 0){
            v.viewed = true;
            if(k + 1 == element.MindMaps.length){
              loaded = 1;
              await this.expandDomain(i+1)
              await this.expandVideo(this.MindMaplistdata[i+1].MindMaps[0], 0)
            }else{
              loaded = 1;
              await this.expandVideo(element.MindMaps[k + 1], k + 1)
            }
          }
        })
      })
    }
    this.changemark();
  }
  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.Allnotes = [];
    this.VideoNotes = [];
    this.txtVideoNotes = "";
    if (window.innerWidth <= 768) {
      document.getElementById("mobile").style.display = "block"
    }
    this.VideoLink = '';
    this.TranscriptData = [];
    await this.updateVideoPercentage();
    this.View_Percentage = 0
    if(this.selectedVideoQuality == '720p' && item.video_link_720p){
      this.VideoLink = item.video_link_720p;
    }else if(this.selectedVideoQuality == '480p' && item.video_link_480p){
      this.VideoLink = item.video_link_480p;
    }else if(this.selectedVideoQuality == '360p' && item.video_link_360p){
      this.VideoLink = item.video_link_360p;
    }else if(this.selectedVideoQuality == '240p' && item.video_link_240p){
      this.VideoLink = item.video_link_240p;
    }else if(this.selectedVideoQuality == '144p' && item.video_link_144p){
      this.VideoLink = item.video_link_144p;
    }else{
      this.VideoLink = item.video_link
    }
    this.videoQualityOptions=[];
    if(item.video_link){ this.videoQualityOptions.push('1080p HD') }
    if(item.video_link_720p){ this.videoQualityOptions.push('720p') }
    if(item.video_link_480p){ this.videoQualityOptions.push('480p') }
    if(item.video_link_360p){ this.videoQualityOptions.push('360p') }
    if(item.video_link_240p){ this.videoQualityOptions.push('240p') }
    if(item.video_link_144p){ this.videoQualityOptions.push('144p') }
    this.VideoTitle = item.name;
    this.SelectedChapters = item.chapters;
    this.SelectedChapters.forEach((element, i) => {
      element['vid'] = item.id;
      i == 0 ? (element['active'] = true) : (element['active'] = false);
    });
    if (
      item.transcript &&
      item.transcript != 'null' &&
      item.transcript != null
    ) {
      this.TranscriptData = JSON.parse(item.transcript);

      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'
        );
      });
    }
    await this.getVideoNotesByUser();
    setTimeout(() => {
      const player = this.EleRef.nativeElement.querySelector('video');
      player.load();
      this.api.playbackRate = this.playback;
      player.addEventListener('timeupdate', this.transcription);
      let me = this;
      player.addEventListener('timeupdate', async function () {
        const audi = document.getElementsByTagName('video');
        me.SelectedChapters.forEach((chapt) => {
          var hms = chapt.FromTime;
          var a = hms.split(':');
          if(a.length == 3){
            var seconds = +a[0] * 60 * 60 + +a[1] * 60 + +a[2];
          }else{
            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;
          }
        });
      });
    }, 100);
  }
  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(':');
    if(a.length == 3){
      var seconds = +a[0] * 60 * 60 + +a[1] * 60 + +a[2];
    }else{
      var seconds = parseInt(a[0]) * 60 + parseInt(a[1]);
    }
    const video = document.getElementsByTagName('video');
    video[0].currentTime = seconds;
  }
  async saveDiscussion() {
    if (
      this.DiscussionText == '' ||
      this.DiscussionText == null ||
      this.DiscussionText == undefined
    ) {
      this.service.ShowError('Message cant not be empty.');
    } 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

            await this.service
              .saveDiscussion(
                this.userid,
                'MIND',
                this.Mindid,
                this.Mindid,
                this.DiscussionText,
                token
              )
              .then(async (data) => {
                if (data[0].status == 200) {
                  var list = JSON.parse(<string>data[0].json);
                  let details = JSON.parse(localStorage.getItem('userdetails'));
                  var disc = {
                    createdAt: list.data.createdAt,
                    id: list.data.id,
                    message: list.data.message,
                    q_id: list.data.q_id,
                    status: list.data.status,
                    test_id: list.data.test_id,
                    test_type: list.data.test_type,
                    user_id: list.data.user_id,
                    user: {
                      avatar_url: details.avatar_url,
                      email: details.email,
                      id: details.id,
                      name: details.name,
                    },
                  };
                  this.MindMaplistdata.forEach((element) => {
                    if (element.id == list.data.id) {
                      element.Discussion.push(disc);
                    }
                  });
                }
                this.DiscussionText = '';
              });
            this.spinner.hide();
          }
        });
    }
  }
  retuey() {
    window.location.reload();
  }
  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');
        this.spinner.show();
        await this.VideoserviceService.GetVideoNotesByUser(
          userId,
          this.Mindid,
          "MIND",
          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();
      }
    });
  }

  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 key codes 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 ? this.api.playbackRate : 1;
    this.cdRef.detectChanges();
  }
  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;
  }
  async updateVideoPercentage() {
    var user_id = localStorage.getItem('CisspUserId');
    var cohort_id = localStorage.getItem('cohort_id');
    var data = {
      type_id: this.Mindid,
      user_id: user_id,
      cohort_id: cohort_id,
      type: 'MIND',
      view_percent: this.View_Percentage,
      is_completed: this.View_Percentage == 100 ? 1 : 0
    };
    let emiter = {
      id: parseInt(this.Mindid),
      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.Mindid == "") {
              this.callViewUpdate = true;
            }
          }
          else {
            this.View_Percentage = 0
          }
        });
      }
    })
  }
  changemark() {
    this.MindMaplistdata.forEach(element => {
      var TotalVideo = 0
      element.MindMaps.forEach(el => {
        if (el.viewed) {
          TotalVideo += 1;
        }
      })
      if (element.MindMaps.length == TotalVideo) {
        element["DomainCheck"] = true;
      }
      else {
        element["DomainCheck"] = false;
      }
    });
  }
  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');
    }
  }
  transcription() {
    const audi = document.getElementsByTagName('video');
    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:#e63a9b;color:#fff');
      }
    }
  }
}
export interface VideoComplete {
  id: number;
  percent: number;
}