import { Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import Swal from 'sweetalert2/dist/sweetalert2.js'
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from "ngx-spinner";
import { Router } from '@angular/router';
import { MatSort } from '@angular/material/sort';
import { AuthorizationService } from '../../service/authorization.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { VideolessonService } from '../../services/videolesson/videolesson.service';
import * as htmlToImage from 'html-to-image';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
@Component({
  selector: 'app-videolesson',
  templateUrl: './videolesson.component.html',
  styleUrls: ['./videolesson.component.scss']
})
export class VideolessonComponent implements OnInit {
  RearrangePopup: boolean = false;
  RearrangeCertificate: any;
  RearrangeSelectedDomain: any;
  RearrangeSelecteSubdDomain: any;
  RearrangeArray = [];
  filterRearrangeArray = [];
  displayedColumns: string[] = ['srno', "video_link", "certificate_name", 'domin_name', 'subdomain_name', 'topic_name', 'video_title', 'duration', 'type', 'actions'];
  dataSource: MatTableDataSource<videolist>;
  Search: any;
  TranscriptPopup: boolean = false;
  TranscriptText: any;
  token: any;
  addVideo: boolean = false;
  IsUpdate: boolean = false;
  @Input('pagination') pagination: boolean;
  @ViewChild(MatPaginator, { static: false }) set matPaginator(paginator: MatPaginator) {
    if (this.pagination) {
      this.dataSource.paginator = paginator;
    }
  }
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild('qrEle') qrEle: ElementRef;
  public VideoLessonForm: FormGroup;

  SelectedCertificate: any;
  SelectedDomain: any;
  SelectedSubDomain: any;
  SelectedTopics: any;
  VideoTitle: any;
  Summary: any;
  VideoThumbnail: any;
  VideoLink: any;
  VideoLink_144p: any;
  VideoLink_240p: any;
  VideoLink_360p: any;
  VideoLink_480p: any;
  VideoLink_720p: any;
  Type: any;
  Duration: any;
  Chapters: any;
  Transcript: any;
  id: any;

  IsShortUrlChange: boolean = false;
  filtersubDomain = [];
  filterDomain = [];
  Domain = [];
  SubDomain = [];
  Topic = [];
  filterTopic = [];
  Certificatelist = [];
  TranscriptArray = [{
    "Text": "",
    "FromTime": "",
    "ToTime": "",
  }];
  ChaptersArray = [{
    "Text": "",
    "FromTime": "",
    "user_ids": ""
  }];
  TopicArray = [{
    "Text": ""
  }];

  loglist = [];
  Qr_Url: any;
  qr_code: any;
  video_lesson_link: any;
  oldAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Video Title": "", "Summary": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Video Length": "" }
  newAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Video Title": "", "Summary": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Video Length": "" }
  auditHistory = "";
  base64 = " "
  constructor(public videoService: VideolessonService, public fb: FormBuilder, public auth: AuthorizationService, public router: Router, public spinner: NgxSpinnerService, public service: ServicesService) {
  }
  downloadQrCode() {
    let me = this;
    htmlToImage.toPng(document.getElementById('video_qrcode'))
      .then(function (dataUrl) {
        var link = document.createElement('a');
        link.download = me.qr_code + '.png';
        link.href = dataUrl;
        link.click();
      });
  }
  convertBase64ToBlobData(base64Data: string, contentType: string = 'image/png', sliceSize = 512) {
    const byteCharacters = atob(base64Data);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);

      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);

      byteArrays.push(byteArray);
    }

    const blob = new Blob(byteArrays, { type: contentType });
    return blob;
  }
  addNewVideo() {
    this.addVideo = true;
  }
  closeModal() {
    this.addVideo = false;
    this.IsUpdate = false;;
    this.SelectedCertificate = "";
    this.SelectedDomain = "";
    this.SelectedSubDomain = "";
    this.VideoTitle = "";
    this.Summary = "";
    this.VideoThumbnail = "";
    this.VideoLink = "";
    this.VideoLink_144p = "";
    this.VideoLink_240p = "";
    this.VideoLink_360p = "";
    this.VideoLink_480p = "";
    this.VideoLink_720p = "";
    this.Type = "";
    this.Duration = "";
    this.Chapters = "";
    this.Transcript = "";
    this.TranscriptArray = [{
      "Text": "",
      "FromTime": "",
      "ToTime": "",
    }];
    this.ChaptersArray = [{
      "Text": "",
      "FromTime": "",
      "user_ids": ""
    }];
    this.qr_code = "";
    this.video_lesson_link = "";
    this.Qr_Url = "";
    this.oldAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Video Title": "", "Summary": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Video Length": "" }
    this.newAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Video Title": "", "Summary": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Video Length": "" }
    this.auditHistory = "";
    this.IsShortUrlChange = false;
  }


  async ngOnInit() {

    this.VideoLessonForm = this.fb.group({
      SelectedCertificate: ['', Validators.required],
      SelectedDomain: ['', Validators.required],
      SelectedSubDomain: ['', Validators.required],
      SelectedTopics: ['', Validators.required],
      VideoTitle: ['', Validators.required],
      VideoThumbnail: ['', Validators.required],
      VideoLink: ['', Validators.required],
      Type: ['', Validators.required],
      Duration: ['', Validators.required],
      VideoLink_720p: new FormControl(),
      VideoLink_480p: new FormControl(),
      VideoLink_360p: new FormControl(),
      VideoLink_240p: new FormControl(),
      VideoLink_144p: new FormControl(),
      Points: new FormControl(),
      Transcript: new FormControl(),
      video_lesson_link: new FormControl(),
      Summary: new FormControl()

    });
    await this.spinner.show();
    try {
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        }
        else {
          // this.token = session.getIdToken().getJwtToken();
          this.token = '';
          this.service.token = this.token;

          await this.GetAllDropdown(this.token);
          await this.spinner.hide();
        }
      });
    }
    catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.message);
    }
  }
  async getAllVideoLesson(token) {
    const users: videolist[] = [];
    this.filterRearrangeArray = [];
    await this.videoService.GetAllVideoLesson(token).then(async (data) => {

      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        
        var srno = 0;
        await list.data.forEach(async (element) => {
          srno = srno + 1;
          this.filterRearrangeArray.push({
            "id": element.id,
            "video_title": element.video_title,
            "video_thumbnil": element.video_thumbnil,
            "topic_list": element.topic_list ? JSON.parse(element.topic_list) : [],
            "duration": element.duration,
            "type": element.type,
            "d_id": element.d_id,
            "sd_id": element.sd_id,
            "c_id": element.c_id,
            "sr_number": element.sr_number
          })

          await users.push({
            "srno": srno,
            "id": element.id,
            "video_title": element.video_title,
            "summary": element.summary,
            "video_link": element.video_link,
            "video_lesson_link_144p": element.video_lesson_link_144p,
            "video_lesson_link_240p": element.video_lesson_link_240p,
            "video_lesson_link_360p": element.video_lesson_link_360p,
            "video_lesson_link_480p": element.video_lesson_link_480p,
            "video_lesson_link_720p": element.video_lesson_link_720p,
            "video_thumbnil": element.video_thumbnil,
            "createdAt": element.createdAt,
            "c_id": element.c_id,
            "d_id": element.d_id,
            "domin_name": element.domain.domin_name,
            "sd_id": element.sd_id,
            "subdomain_name": this.filtersubDomain.filter(el => { return element.sd_id.find(element => { return element == el.id; }); }).map(function (item) { return item.subdomain_name; }).join(", "),
            "type": element.type,
            "transcript_link": element.transcript_link,
            "chapters": element.chapters,
            "duration": element.duration,
            "certi_id": element.certi_id,
            "certificate_name": element.certificate.certificate_name,
            "qr_code": element.qr_code,
            "video_lesson_link": element.video_lesson_link,
            "topic_list": element.topic_list,
            "topic_id": element.topic_id,
            "topic_name": this.filterTopic.filter(el => { return element.topic_id.find(element => { return element == el.id; }); }).map(function (item) { return item.topic_name; }).join(", "),
            "bkp_sd_id": element.bkp_sd_id
          });
        });
        this.dataSource = new MatTableDataSource(users);
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
        this.filter();
        this.pagination = true;
      }
    });
  }
  async GetAllDropdown(token) {
    await this.service.GetAllDropdown(token).then(async (data) => {


      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        this.Domain = list.data.Domain;
        this.filterDomain = list.data.Domain;
        this.SubDomain = list.data.SubDomain;
        this.filtersubDomain = list.data.SubDomain;
        this.Certificatelist = list.data.Certificate;
        this.Topic = list.data.Topic;
        this.filterTopic = list.data.Topic;

        this.SelectedCertificate = "";
        this.SelectedSubDomain = "";
        this.SelectedDomain = "";
        this.SelectedTopics = "";
        this.Type = "";
        await this.getAllVideoLesson(this.token);

      }
    })
  }
  async filter() {
    this.dataSource.filter = this.Search;
    if (this.pagination) {
      this.dataSource.paginator._changePageSize(this.dataSource.paginator.pageSize);
    }
  }
  async openTranscriptPopup(item) {
    this.TranscriptArray = [];
    this.TranscriptPopup = true;
    this.TranscriptArray = JSON.parse(item.transcript_link);
  }
  closeTranscriptPopup() {
    this.TranscriptPopup = false;
    this.TranscriptArray = [];
  }
  async deleteVideoLesson(item) {
    Swal.fire({
      title: 'Are you sure?',
      text: "delete this video lesson!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Delete'
    }).then(async (result) => {
      if (result.value) {
        this.spinner.show();
        this.auth.getAuthenticatedUser().getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();

            this.router.navigate(['/login']);
          }
          else {
            var token = ''
            await this.videoService.deleteVideoLesson(item.id, token).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.auth.getAuthenticatedUser().getSession(async (err, session) => {
                  if (err) {
                    await this.spinner.hide();

                    this.router.navigate(['/login']);
                  }
                  else {
                    var token = ''
                    var e = window.localStorage.getItem("adminUser");
                    if (e == null || e == undefined || e == "") {
                      e = 'admin';
                    }
                    var desc = "<span> " + item.video_title + "</span> Video lesson is deleted by <span> " + e + "</span>";
                    await this.service.addAdminLogs(desc, "videoleasson", item.id, token);

                  }
                });
                await this.getAllVideoLesson(this.token);
                this.service.ShowSuccess("Video deleted successfully");
              }
            });
          }
        })
        this.spinner.hide();
      }
    })
  }
  async editVideoLesson(item) {
    this.loglist = [];
    await this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      }
      else {

        var token = ''
        this.service.get_logs("videoleasson", item.id, token).then(async (value) => {
          if (value[0].status == 200) {
            var list = JSON.parse(<string>value[0].json);

            this.loglist = list.data;
            await this.spinner.hide();
          }
          else {
            var list = JSON.parse(<string>value[0].json);
            await this.spinner.hide();

            this.service.ShowError(list.message);
          }

        }, err => {
          this.spinner.hide();
        })
      }
    })
    this.addVideo = true;
    this.IsUpdate = true;
    this.id = item.id;
    this.SelectedCertificate = item.certi_id;
    this.SelectedDomain = item.d_id;
    if (item.sd_id) {
      this.SelectedSubDomain = item.sd_id.map(Number);
    }
    if (item.topic_id) {
      this.SelectedTopics = item.topic_id.map(Number);
    }
    this.VideoTitle = item.video_title;
    this.Summary = item.summary;
    this.VideoThumbnail = item.video_thumbnil;
    this.VideoLink = item.video_link;
    this.VideoLink_720p = item.video_lesson_link_720p;
    this.VideoLink_480p = item.video_lesson_link_480p;
    this.VideoLink_360p = item.video_lesson_link_360p;
    this.VideoLink_240p = item.video_lesson_link_240p;
    this.VideoLink_144p = item.video_lesson_link_144p;
    
    this.Type = item.type == "FREE" ? "1" : "2";
    this.Duration = item.duration;

    this.TranscriptArray = JSON.parse(item.transcript_link);
    if (item.chapters == "") {
      this.ChaptersArray = [{
        "Text": "",
        "FromTime": "",
        "user_ids": ""
      }];
    } else {
      this.ChaptersArray = JSON.parse(item.chapters);
    }
    if (item.topic_list == "" || item.topic_list == null) {
      this.TopicArray = [{
        "Text": ""
      }];
    } else {
      this.TopicArray = JSON.parse(item.topic_list);
    }
    this.qr_code = item.qr_code;
    this.video_lesson_link = "https://www.dcgo.ca/" + this.qr_code;
    this.Qr_Url = this.video_lesson_link;
    this.IsShortUrlChange = true;
    this.Domain = this.filterDomain.filter(x => x.certi_id == this.SelectedCertificate);
    this.SubDomain = this.filtersubDomain.filter(x => x.d_id == this.SelectedDomain);
    this.Topic = this.filterTopic.filter(el => {
      return this.SelectedSubDomain.find(element => {
        return element == el.sd_id;
      });
    });

    this.oldAuditValueArray = { "Certificate": this.Certificatelist.find(x => x.id == this.SelectedCertificate) ? this.Certificatelist.find(x => x.id == this.SelectedCertificate).certificate_name : '', "Domain": this.filterDomain.find(x => x.id == this.SelectedDomain) ? this.filterDomain.find(x => x.id == this.SelectedDomain).domin_name : '', "Subdomain": this.filtersubDomain.find(x => x.id == this.SelectedSubDomain) ? this.filtersubDomain.find(x => x.id == this.SelectedSubDomain).subdomain_name : '', "Topic": this.Topic.filter((item) => { return this.SelectedTopics.includes(item.id) }).map(function (elem) { return elem.topic_name; }).join(","), "Video Title": this.VideoTitle, "Summary": this.Summary, "Thumbnail": this.VideoThumbnail, "CDN Link": this.VideoLink, "Video Link": this.video_lesson_link, "Type": this.Type, "Video Length": this.Duration }
  }
  changeSubDomain(ev) {
    if (ev.length > 0) {
      this.Topic = this.filterTopic.filter(el => {
        return ev.find(element => {
          return element.id == el.sd_id;
        });
      });
      this.SelectedTopics = this.Topic.filter(el => {
        if (this.SelectedTopics) {
          return this.SelectedTopics.find(element => {
            return element == el.id;
          });
        }
      }).map(function (item) {
        return item.id;
      });
      if (!this.IsShortUrlChange) {
        var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let ids = "D";
        for (let id = 0; id < 3; id++) {
          ids += chars[Math.floor(Math.random() * chars.length)];
        }
        this.qr_code = ids;
        this.video_lesson_link = "https://www.dcgo.ca/" + ids;
        this.Qr_Url = this.video_lesson_link;
        this.SelectedTopics = "";
      }
    }
    else {
      this.Topic = this.filterTopic;
      this.SelectedTopics = "";
    }
  }
  async domainchange(ev) {
    const val = ev.target.value;
    if (val && val.trim() != '') {
      this.SubDomain = this.filtersubDomain.filter((itemset) => {
        return (
          itemset.d_id == val
        );
      })
      if (!this.IsShortUrlChange) {
        var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let ids = "D";
        for (let id = 0; id < 3; id++) {
          ids += chars[Math.floor(Math.random() * chars.length)];
        }
        this.qr_code = ids;
        this.video_lesson_link = "https://www.dcgo.ca/" + ids;
        this.Qr_Url = this.video_lesson_link;
        this.SelectedSubDomain = "";
        this.SelectedTopics = "";
      }
    }
    else {
      this.SelectedDomain = "";
      this.SelectedSubDomain = "";
      this.SubDomain = this.filtersubDomain;
    }
  }
  onCertificateChange(ev) {
    const val = ev.target.value;
    if (val && val.trim() != '') {
      this.Domain = this.filterDomain.filter((data) => {
        return (
          data.certi_id == val
        );
      })
      this.SelectedDomain = "";
      this.SelectedSubDomain = "";
      this.SelectedTopics = "";
    }
    else {
      this.Domain = this.filterDomain;
    }
  }

  addAnotherTranscript() {
    this.TranscriptArray.push({
      "Text": "",
      "FromTime": "",
      "ToTime": "",
    })

  }
  addAnotherChapters() {
    this.ChaptersArray.push({
      "Text": "",
      "FromTime": "",
      "user_ids": ""
    })

  }
  addAnotherTopic() {
    this.TopicArray.push({
      "Text": ""
    })
  }
  DeleteTranscript(item) {
    const index = this.TranscriptArray.indexOf(item);
    if (index > -1) {
      this.TranscriptArray.splice(index, 1);
    }
  }
  DeleteChapters(item) {
    const index = this.ChaptersArray.indexOf(item);
    if (index > -1) {
      this.ChaptersArray.splice(index, 1);
    }
  }
  DeleteTopic(item) {
    const index = this.TopicArray.indexOf(item);
    if (index > -1) {
      this.TopicArray.splice(index, 1);
    }
  }
  linkChange() {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let ids = "D";
    for (let id = 0; id < 3; id++) {
      ids += chars[Math.floor(Math.random() * chars.length)];
    }
    this.qr_code = ids;
    this.video_lesson_link = "https://www.dcgo.ca/" + ids;
    this.Qr_Url = this.video_lesson_link;
  }
  async addVideoLesson() {

    if (this.VideoLessonForm.valid) {

      var video_link = this.VideoLink,
        video_lesson_link_720p = this.VideoLink_720p,
        video_lesson_link_480p = this.VideoLink_480p,
        video_lesson_link_360p = this.VideoLink_360p,
        video_lesson_link_240p = this.VideoLink_240p,
        video_lesson_link_144p = this.VideoLink_144p,
        video_title = this.VideoTitle,
        summary = this.Summary,
        video_thumbnil = this.VideoThumbnail,
        d_id = this.SelectedDomain,
        sd_id = this.SelectedSubDomain.toString(),
        topic_id = this.SelectedTopics.toString(),
        type = this.Type + "",
        transcript_link = JSON.stringify(this.TranscriptArray),
        chapters = JSON.stringify(this.ChaptersArray);
      if (this.ChaptersArray.length == 1) {
        this.ChaptersArray.forEach(element => {
          if (element.Text == "") {
            chapters = "";
          }
        });
      }
      let topic_list = JSON.stringify(this.TopicArray);;
      if (this.TopicArray.length == 1) {
        this.TopicArray.forEach(element => {
          if (element.Text == "") {
            topic_list = "";
          }
        });
      }
      this.spinner.show();
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        }
        else {
          var token = ''
          await this.videoService.AddVideoLesson(video_link, video_lesson_link_720p, video_lesson_link_480p, video_lesson_link_360p, video_lesson_link_240p, video_lesson_link_144p, video_title, summary, video_thumbnil, "", d_id, sd_id, topic_id, "1", type, transcript_link, "1", token, "0", this.SelectedCertificate, this.Duration, chapters, this.qr_code, topic_list).then(async (value) => {
            if (value[0].status == 200) {

              this.auth.getAuthenticatedUser().getSession(async (err, session) => {
                if (err) {
                  await this.spinner.hide();

                  this.router.navigate(['/login']);
                }
                else {
                  var list = JSON.parse(<string>value[0].json);

                  var token = ''
                  var e = window.localStorage.getItem("adminUser");
                  if (e == null || e == undefined || e == "") {
                    e = 'admin';
                  }
                  var desc = "<span> " + this.VideoTitle + "</span> Video lesson is added by <span> " + e + "</span>";
                  await this.service.addAdminLogs(desc, "videoleasson", list.data.id, token);
                }
              });
              this.IsUpdate = false;
              this.addVideo = false;
              this.closeModal();
              await this.getAllVideoLesson(token);
              this.service.ShowSuccess("Video Added Successfully");
            }
          })
        }
      })
      this.spinner.hide();

    }
  }
  async updateVideoLesson() {
    if (this.VideoLessonForm.valid) {
      var video_link = this.VideoLink,
        video_lesson_link_720p = this.VideoLink_720p,
        video_lesson_link_480p = this.VideoLink_480p,
        video_lesson_link_360p = this.VideoLink_360p,
        video_lesson_link_240p = this.VideoLink_240p,
        video_lesson_link_144p = this.VideoLink_144p,
        video_title = this.VideoTitle,
        summary = this.Summary,
        video_thumbnil = this.VideoThumbnail,
        d_id = this.SelectedDomain,
        sd_id = this.SelectedSubDomain.toString(),
        topic_id = this.SelectedTopics.toString(),
        type = this.Type + "",
        transcript_link = JSON.stringify(this.TranscriptArray);

      let chapters = JSON.stringify(this.ChaptersArray);
      if (this.ChaptersArray.length == 1) {
        this.ChaptersArray.forEach(element => {
          if (element.Text == "") {
            chapters = "";
          }
        });
      }
      let topic_list = JSON.stringify(this.TopicArray);;
      if (this.TopicArray.length == 1) {
        this.TopicArray.forEach(element => {
          if (element.Text == "") {
            topic_list = "";
          }
        });
      }
      this.spinner.show();
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        }
        else {
          var token = ''
          var link = this.video_lesson_link.split('https://www.dcgo.ca/');
          var qr = link.length > 1 ? link[1] : this.qr_code;

          await this.videoService.UpdateVideoLesson(this.id, video_link, video_lesson_link_720p, video_lesson_link_480p, video_lesson_link_360p, video_lesson_link_240p, video_lesson_link_144p, video_title, summary, video_thumbnil, "", d_id, sd_id, topic_id, "1", type, transcript_link, "1", token, "0", this.SelectedCertificate, this.Duration, chapters, qr, topic_list).then(async (value) => {
            if (value[0].status == 200) {
              this.auth.getAuthenticatedUser().getSession(async (err, session) => {
                if (err) {
                  await this.spinner.hide();

                  this.router.navigate(['/login']);
                }
                else {
                  var token = ''
                  var e = window.localStorage.getItem("adminUser");
                  if (e == null || e == undefined || e == "") {
                    e = 'admin';
                  }
                  this.newAuditValueArray = { "Certificate": this.Certificatelist.find(x => x.id == this.SelectedCertificate) ? this.Certificatelist.find(x => x.id == this.SelectedCertificate).certificate_name : '', "Domain": this.filterDomain.find(x => x.id == this.SelectedDomain) ? this.filterDomain.find(x => x.id == this.SelectedDomain).domin_name : '', "Subdomain": this.filtersubDomain.find(x => x.id == this.SelectedSubDomain) ? this.filtersubDomain.find(x => x.id == this.SelectedSubDomain).subdomain_name : '', "Topic": this.Topic.filter((item) => { return this.SelectedTopics.includes(item.id) }).map(function (elem) { return elem.topic_name; }).join(","), "Video Title": this.VideoTitle, "Summary": this.Summary, "Thumbnail": this.VideoThumbnail, "CDN Link": this.VideoLink, "Video Link": this.video_lesson_link, "Type": this.Type, "Video Length": this.Duration }
                  var audit = this.auth.compareAuditHist(this.oldAuditValueArray, this.newAuditValueArray);
                  var desc = audit;
                  await this.service.addAdminLogs(desc, "videoleasson", this.id, token);

                }
              });
              this.IsUpdate = false;
              this.addVideo = false;
              this.closeModal();
              await this.getAllVideoLesson(token);
              this.service.ShowSuccess("Video Update Successfully");
            }
          })
        }
      })
      this.spinner.hide();
    }
  }
  validateFromTime(item, event) {
    let len = item.FromTime.length;
    if (event.keyCode != 8) {
      if (event.keyCode == 46) {
        if (item.FromTime.includes(":")) {
          item.FromTime = item.FromTime.replace(":", "");
          let f = item.FromTime.substr(0, 2)
          let s = item.FromTime.substr(2, len)
          item.FromTime = f + ":" + s;
        }
      }
      if (len >= 5) {
        item.FromTime = item.FromTime.substr(0, 5)
        let first = item.FromTime.split(":")[0]
        let second = item.FromTime.split(":")[1]
        if (first > 59) {
          first = 59
        }
        if (second > 59) {
          second = 59
        }
        item.FromTime = first + ":" + second;
      } else if (len == 2) {
        let out = item.FromTime.replace(/(.{2})$/, '$1:');
        item.FromTime = out;
      } else if (!item.FromTime.includes(":") && len > 2) {
        let f = item.FromTime.substr(0, 2)
        let s = item.FromTime.substr(2, len)
        item.FromTime = f + ":" + s;
      }
    } else {
      if (item.FromTime.includes(":")) {
        if (item.FromTime.indexOf(":") != 2) {
          item.FromTime = item.FromTime.replace(":", "");
          let f = item.FromTime.substr(0, 2)
          let s = item.FromTime.substr(2, len)
          item.FromTime = f + ":" + s;
        }
      }
    }
  }
  validateToTime(item, event) {
    let len = item.ToTime.length;
    if (event.keyCode != 8) {
      if (event.keyCode == 46) {
        if (item.ToTime.includes(":")) {
          item.ToTime = item.ToTime.replace(":", "");
          let f = item.ToTime.substr(0, 2)
          let s = item.ToTime.substr(2, len)
          item.ToTime = f + ":" + s;
        }
      }
      if (len >= 5) {
        item.ToTime = item.ToTime.substr(0, 5)
        let first = item.ToTime.split(":")[0]
        let second = item.ToTime.split(":")[1]
        if (first > 59) {
          first = 59
        }
        if (second > 59) {
          second = 59
        }
        item.ToTime = first + ":" + second;
      } else if (len == 2) {
        let out = item.ToTime.replace(/(.{2})$/, '$1:');
        item.ToTime = out;
      } else if (!item.ToTime.includes(":") && len > 2) {
        let f = item.ToTime.substr(0, 2)
        let s = item.ToTime.substr(2, len)
        item.ToTime = f + ":" + s;
      }
    } else {
      if (item.ToTime.includes(":")) {
        if (item.ToTime.indexOf(":") != 2) {
          item.ToTime = item.ToTime.replace(":", "");
          let f = item.ToTime.substr(0, 2)
          let s = item.ToTime.substr(2, len)
          item.ToTime = f + ":" + s;
        }
      }
    }
  }
  async closeRearrangeModal() {
    this.RearrangePopup = false;
    this.RearrangeArray = [];
    this.RearrangeCertificate = "";
    this.RearrangeSelectedDomain = "";
    this.RearrangeSelecteSubdDomain = "";
  }
  async openRearrangePopup() {
    this.RearrangePopup = true;
    this.RearrangeArray = [];
    this.RearrangeCertificate = "";
    this.RearrangeSelectedDomain = "";
    this.RearrangeSelecteSubdDomain = "";
  }
  async saveRearrange() {
    let request = [];
    this.RearrangeArray.forEach((element, i) => {
      element.sr_number = i;
      request.push({
        "id": element.id,
        "sr_number": i
      })
    });
    this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      }
      else {
        var token = ''
        await this.videoService.saveRearrangeVide(request, token).then(async (data) => {
          if (data[0].status == 200) {
            await this.getAllVideoLesson(token);
            await this.closeRearrangeModal();
            this.spinner.hide();
          } else {
            this.spinner.hide();
          }
        });
      }
    })
  }
  async onRearrangeCertificateChange() {
    const val = this.RearrangeCertificate;
    if (val && val.trim() != '') {
      this.Domain = this.filterDomain.filter((data) => {
        return (
          data.certi_id.toString().toLowerCase() == (val.toLowerCase())
        );
      })
    }
    else {
      this.Domain = this.filterDomain;
    }
  }
  async RearrangeDomainChange() {
    const val = this.RearrangeSelectedDomain;
    if (val && val.trim() != '') {
      this.SubDomain = this.filtersubDomain.filter((itemset) => {
        return (
          itemset.d_id.toString().toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      })
    }
    else {
      this.SelectedDomain = "";
      this.SelectedSubDomain = "";
      this.SubDomain = this.filtersubDomain;
    }
  }
  RearrangeSubDomainChange() {
    const val = this.RearrangeSelecteSubdDomain;
    if (val && val.trim() != '') {
      this.RearrangeArray = this.filterRearrangeArray.filter((data) => {
        return (
          data.sd_id.toString().toLowerCase() == (val.toLowerCase())
        );
      })
    }
    this.RearrangeArray.sort((a, b) => (a.sr_number > b.sr_number ? 1 : -1));
  }
  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(
      this.RearrangeArray,
      event.previousIndex,
      event.currentIndex
    );
  }
}
export interface videolist {
  srno: number;
  id: string;
  video_title: string;
  summary: string;
  video_link: string;
  video_lesson_link_144p: string;
  video_lesson_link_240p: string;
  video_lesson_link_360p: string;
  video_lesson_link_480p: string;
  video_lesson_link_720p: string;
  video_thumbnil: string
  createdAt: string;
  c_id: number;
  d_id: number;
  domin_name: string;
  sd_id: number;
  subdomain_name: string;
  topic_id: string;
  type: string;
  transcript_link: string;
  chapters: string;
  duration: string;
  certi_id: string;
  certificate_name: string;
  qr_code: string;
  video_lesson_link: string;
  topic_list: string;
  topic_name: string;
  bkp_sd_id: string;
}