import { Component, 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 { ActivatedRoute, Router } from '@angular/router';
import { MatSort } from '@angular/material/sort';
import { AuthorizationService } from '../../service/authorization.service';
import { FormBuilder, FormControl, FormGroup, Validators, FormArray } from '@angular/forms';
import { MindmapService } from '../../services/mindmap/mindmap.service';
import * as htmlToImage from 'html-to-image';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
@Component({
  selector: 'app-mindmaps',
  templateUrl: './mindmaps.component.html',
  styleUrls: ['./mindmaps.component.scss']
})
export class MindmapsComponent implements OnInit {
  RearrangePopup: boolean = false;
  RearrangeCertificate: any;
  RearrangeSelectedDomain: any;
  RearrangeArray = [];
  filterRearrangeArray = [];
  displayedColumns: string[] = ['srno', 'certificate_name', 'domin_name', 'subdomain_name', 'name', 'maps', 'actions'];
  dataSource: MatTableDataSource<videolist>;
  Search: any;
  TranscriptPopup: boolean = false;
  token: any;
  DescriptionView: any;

  public VideoLessonForm: FormGroup;
  IsUpdate: boolean = false;
  id: any;
  Domain = [];
  SubDomain = [];
  SelectedSubDomain: any;
  SelectedDomain: any;
  name: any;
  description: any;
  ViewMap: boolean = false;
  filterDomain = [];
  filtersubDomain = [];
  Certificatelist = [];
  SelectedCertificate: any;
  Thumbnail: any;
  VideoLink: any;
  VideoLink_144p: any;
  VideoLink_240p: any;
  VideoLink_360p: any;
  VideoLink_480p: any;
  VideoLink_720p: any;
  Transcript: any;
  Duration: any;
  TranscriptArray = [{
    "Text": "",
    "FromTime": "",
    "ToTime": "",
  }];
  ChaptersArray = [{
    "Text": "",
    "FromTime": "",
    "user_ids": ""
  }];

  loglist = [];
  SelectedTopics: any;
  Topic = [];
  filterTopic = [];
  mindmap_link: any;
  Qr_Url: any;
  qr_code: any;
  oldAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Mindmap Title": "", "MindMap HTML Code": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Length": "" }
  newAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Mindmap Title": "", "MindMap HTML Code": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Length": "" }
  auditHistory = "";
  base64 = " "
  @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;

  constructor(public mindMapService: MindmapService, public fb: FormBuilder, public ActiveRoute: ActivatedRoute, public auth: AuthorizationService, public router: Router, public spinner: NgxSpinnerService, public service: ServicesService) {}
  async ngOnInit() {

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

          this.router.navigate(['/login']);
        }
        else {
          var token = ''
          this.service.token = token;
          await this.GetAllDropdown(token);
          await this.GetAllMindMaps(token);
          await this.spinner.hide();
        }
      });
    }
    catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.message);
    }
    this.VideoLessonForm = this.fb.group({
      SelectedSubDomain: ['', Validators.required],
      SelectedDomain: ['', Validators.required],
      name: ['', Validators.required],
      Thumbnail: ['', Validators.required],
      VideoLink: ['', Validators.required],
      description: ['', Validators.required],
      SelectedCertificate: ['', 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(),
      SelectedTopics: new FormControl(),
      mindmap_link: new FormControl()
    });
  }
  openTranscriptPopup() {
    this.TranscriptPopup = true;
    this.IsUpdate = false;
  }
  async GetAllMindMaps(token) {
    const users: videolist[] = [];
    this.filterRearrangeArray = [];
    await this.mindMapService.GetAllMindMaps(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,
            "name": element.name,
            "thumbnail_link": element.thumbnail_link,
            "d_id": element.d_id,
            "sd_id": element.sd_id,
            "certi_id": element.certi_id,
            "sr_number": element.sr_number
          })

          await users.push({
            "srno": srno,
            "id": element.id,
            "name": element.name,
            "description": element.description,
            "domin_name": element.domain.domin_name,
            "subdomain_name": this.filtersubDomain.filter(el => { return element.sd_id.find(element => { return element == el.id; }); }).map(function (item) { return item.subdomain_name; }).join(", "),
            "d_id": element.domain.id,
            "sd_id": element.sd_id,
            "certi_id": element.certi_id,
            "certificate_name": element.certificate.certificate_name,
            "chapters": element.chapters,
            "thumbnail_link": element.thumbnail_link,
            "transcript": element.transcript,
            "video_link": element.video_link,
            "video_link_720p": element.video_link_720p,
            "video_link_480p": element.video_link_480p,
            "video_link_360p": element.video_link_360p,
            "video_link_240p": element.video_link_240p,
            "video_link_144p": element.video_link_144p,
            "duration": element.duration,
            "topic_id": element.topic_id,
            "qr_code": element.qr_code,
            "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;
      }
    });
  }
  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;
      });

    }
    else {
      this.Topic = this.filterTopic;
      this.SelectedTopics = "";
    }
  }
  async filter() {
    this.dataSource.filter = this.Search;
    if (this.pagination) {
      this.dataSource.paginator._changePageSize(this.dataSource.paginator.pageSize);
    }
  }
  closeTranscriptPopup() {
    this.TranscriptPopup = false;
    this.IsUpdate = false;
    this.id = "";
    this.SelectedSubDomain = "";
    this.SelectedDomain = "";
    this.name = "";
    this.description = "";
    this.SelectedCertificate = "";
    this.Thumbnail = "";
    this.VideoLink = "";
    this.VideoLink_144p = "";
    this.VideoLink_240p = "";
    this.VideoLink_360p = "";
    this.VideoLink_480p = "";
    this.VideoLink_720p = "";
    this.Duration = "";
    this.TranscriptArray = [{
      "Text": "",
      "FromTime": "",
      "ToTime": "",
    }];
    this.ChaptersArray = [{
      "Text": "",
      "FromTime": "",
      "user_ids": ""
    }]
    this.qr_code = "";
    this.mindmap_link = "";
    this.Qr_Url = "";
    this.oldAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Mindmap Title": "", "MindMap HTML Code": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Length": "" }
    this.newAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Mindmap Title": "", "MindMap HTML Code": "", "Thumbnail": "", "CDN Link": "", "Video Link": "", "Type": "", "Length": "" }
    this.auditHistory = "";
  }
  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();
      });
  }
  async deleteReference(item) {
    Swal.fire({
      title: 'Are you sure?',
      text: "delete this Mind Maps!",
      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.mindMapService.DeleteMindMaps(item.id, token).then(async (data) => {
              if (data[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';
                    }
                    var desc = "<span> " + item.web_link + "</span> Mind maps is deleted by <span> " + e + "</span>";
                    await this.service.addAdminLogs(desc, "mindmap", item.id, token);

                  }
                });
                await this.GetAllMindMaps(this.token);
                this.service.ShowSuccess("Mind maps deleted successfully");
              }
            });
          }
        })
        this.spinner.hide();
      }
    })
  }
  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.name = "";
        this.description = "";
      }
    })
  }
  async domainchange(ev) {
    const val = ev.target.value;
    if (val && val.trim() != '') {
      this.SubDomain = this.filtersubDomain.filter((itemset) => {
        return (
          itemset.d_id.toString().toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      })
      this.SelectedSubDomain = "";
      this.SelectedTopics = "";
    }
    else {
      this.SelectedDomain = "";
      this.SelectedSubDomain = "";
      this.SelectedTopics = "";
      this.SubDomain = this.filtersubDomain;
    }
  }
  markFormTouched(group: FormGroup | FormArray) {
    Object.keys(group.controls).forEach((key: string) => {
      const control = group.controls[key];
      if (control instanceof FormGroup || control instanceof FormArray) { control.markAsTouched(); this.markFormTouched(control); }
      else { control.markAsTouched(); };
    });
  };
  async saveMindMaps() {
    this.markFormTouched(this.VideoLessonForm);

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

          this.router.navigate(['/login']);
        }
        else {
          var token = ''
          let transcript = 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_id = this.SelectedTopics;
          await this.mindMapService.AddMindMaps(this.SelectedDomain, this.SelectedSubDomain.toString(), this.name, this.description, this.SelectedCertificate, this.Thumbnail, this.VideoLink, this.VideoLink_720p, this.VideoLink_480p, this.VideoLink_360p, this.VideoLink_240p, this.VideoLink_144p, chapters, transcript, this.Duration, topic_id.toString(), this.qr_code, token).then(async (value) => {
            if (value[0].status == 200) {
              var list = JSON.parse(<string>value[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> " + this.name + " </span> Mind maps is added by <span> " + e + "</span>";
                  await this.service.addAdminLogs(desc, "mindmap", list.data.id, token);

                }
              });
              this.IsUpdate = false;
              this.TranscriptPopup = false;
              this.closeTranscriptPopup();
              await this.GetAllMindMaps(token);
              await this.spinner.hide();
              this.service.ShowSuccess("Mind maps added successfully");

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

  }
  ViewMapPopup(description) {
    this.ViewMap = true;
    this.DescriptionView = description;
  }
  onCertificateChange(ev) {
    const val = ev.target.value;
    if (val && val.trim() != '') {
      this.Domain = this.filterDomain.filter(x => x.certi_id == val)
      this.SelectedDomain = "";
      this.SelectedSubDomain = "";
      this.SelectedTopics = "";
    }
    else {
      this.SelectedDomain = "";
      this.SelectedSubDomain = "";
      this.SelectedTopics = "";
      this.Domain = this.filterDomain;
    }
  }
  async updateMindMaps() {
    if (this.VideoLessonForm.valid) {
      await this.spinner.show();
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();

          this.router.navigate(['/login']);
        }
        else {
          var token = ''
          let transcript = 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_id = this.SelectedTopics;
          var link = this.mindmap_link.split('https://www.dcgo.ca/m/');
          var qr = link.length > 1 ? link[1] : this.qr_code;
          await this.mindMapService.UpdateMindMaps(this.id, this.SelectedDomain, this.SelectedSubDomain.toString(), this.name, this.description, this.SelectedCertificate, this.Thumbnail, this.VideoLink, this.VideoLink_720p, this.VideoLink_480p, this.VideoLink_360p, this.VideoLink_240p, this.VideoLink_144p, chapters, transcript, this.Duration, topic_id.toString(), qr, token).then(async (value) => {
            if (value[0].status == 200) {
              var list = JSON.parse(<string>value[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';
                  }
                  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(","), "Mindmap Title": this.name, "MindMap HTML Code": this.description, "Thumbnail": this.Thumbnail, "CDN Link": this.VideoLink, "Video Link": this.Qr_Url, "Type": "", "Length": this.Duration }
                  var audit = this.auth.compareAuditHist(this.oldAuditValueArray, this.newAuditValueArray);
                  var desc = audit;
                  await this.service.addAdminLogs(desc, "mindmap", this.id, token);

                }
              });
              this.IsUpdate = false;
              this.TranscriptPopup = false;
              this.closeTranscriptPopup();
              await this.GetAllMindMaps(token);
              await this.spinner.hide();
              this.service.ShowSuccess("Mind Maps update successfully");

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

  }
  async editReference(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("mindmap", 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.IsUpdate = true;
    this.TranscriptPopup = true;
    this.id = item.id;
    this.SelectedDomain = item.d_id;
    if (item.sd_id) {
      this.SelectedSubDomain = item.sd_id.map(Number);
    }
    this.name = item.name;
    this.description = item.description;
    this.SelectedCertificate = item.certi_id;
    this.Thumbnail = item.thumbnail_link;
    this.VideoLink = item.video_link;
    this.VideoLink_720p = item.video_link_720p;
    this.VideoLink_480p = item.video_link_480p;
    this.VideoLink_360p = item.video_link_360p;
    this.VideoLink_240p = item.video_link_240p;
    this.VideoLink_144p = item.video_link_144p;
    this.Duration = item.duration;
    if (item.topic_id) {
      this.SelectedTopics = item.topic_id.map(Number);
    }

    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(","), "Mindmap Title": this.name, "MindMap HTML Code": this.description, "Thumbnail": this.Thumbnail, "CDN Link": this.VideoLink, "Video Link": this.Qr_Url, "Type": "", "Length": this.Duration }
    this.TranscriptArray = JSON.parse(item.transcript);
    
    if (item.chapters == "") {
      this.ChaptersArray = [{
        "Text": "",
        "FromTime": "",
        "user_ids": ""
      }];
    } else {
      this.ChaptersArray = JSON.parse(item.chapters);
    }
    this.qr_code = item.qr_code;
    this.mindmap_link = "https://www.dcgo.ca/m/" + this.qr_code;
    this.Qr_Url = this.mindmap_link;
  }
  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.mindmap_link = "https://www.dcgo.ca/m/" + ids;
    this.Qr_Url = this.mindmap_link;
  }
  addAnotherTranscript() {
    this.TranscriptArray.push({
      "Text": "",
      "FromTime": "",
      "ToTime": "",
    })

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

  }
  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);
    }
  }
  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 = "";
  }
  async openRearrangePopup() {
    this.RearrangePopup = true;
    this.RearrangeArray = [];
    this.RearrangeCertificate = "";
    this.RearrangeSelectedDomain = "";
  }
  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.mindMapService.saveRearrangeVide(request, token).then(async (data) => {
          if (data[0].status == 200) {
            await this.GetAllMindMaps(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.RearrangeArray = this.filterRearrangeArray.filter((data) => {
        return (
          data.d_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;
  name: string,
  description: string;
  domin_name: string,
  subdomain_name: string;
  d_id: number;
  sd_id: number;
  certi_id: string;
  certificate_name: string;
  thumbnail_link: string;
  video_link: string;
  video_link_720p: string;
  video_link_480p: string;
  video_link_360p: string;
  video_link_240p: string;
  video_link_144p : string;
  chapters: string;
  transcript: string;
  duration: string;
  topic_id: string;
  qr_code: string;
  bkp_sd_id: string;
}