import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { ServicesService } from 'src/app/services.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { NgxSpinnerService } from 'ngx-spinner';
import { VideoserviceService } from 'src/app/services/video/videoservice.service';
import { AuthserviceService } from 'src/app/authservice.service';
import { Router } from '@angular/router';
import { VgApiService } from '@videogular/ngx-videogular/core';
import {
  CalendarOptions,
  GoogleCalendar,
  ICalendar,
  OutlookCalendar,
  YahooCalendar,
} from 'datebook';
import * as momentZone from 'moment-timezone';
import { TZone } from 'moment-timezone-picker';

@Component({
  selector: 'app-live-support',
  templateUrl: './live-support.component.html',
  styleUrls: ['./live-support.component.scss'],
})
export class LiveSupportComponent implements OnInit {
  openVideoPopup: boolean = false;
  api: VgApiService;
  playback: any;
  VideoLink: string = '';
  defaultPath: string =
    'https://recordings-new.s3.us-east-2.amazonaws.com/captures/';
  currentIndex = 0;
  playList = [];
  currentItem: any;
  nextLiveCall: any;
  showJoinButton: boolean = false;
  isBefore15: boolean = false;
  noEvent: boolean = true;
  dataSource: MatTableDataSource<supportList>;
  dayNames = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
  ];
  monthsNames = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sept',
    'Oct',
    'Nov',
    'Dec',
  ];
  timezone: any = JSON.parse(<string>localStorage.getItem('userdetails'))
    .user_time_zone
    ? JSON.parse(
      JSON.parse(<string>localStorage.getItem('userdetails')).user_time_zone
    )
    : this.formatZone(momentZone.tz.guess(true));
  recordingsData = [];
  premierMasterClass: boolean;
  userAmount: any;
  noOfWay: string;
  showControls: boolean = false;
  timer: any;
  @Input('pagination') pagination: boolean;
  @ViewChild(MatPaginator, { static: false }) set matPaginator(
    paginator: MatPaginator
  ) {
    if (this.pagination) {
      this.dataSource.paginator = paginator;
    }
  }
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  displayedColumns: string[] = ['name'];
  constructor(
    public router: Router,
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public videoService: VideoserviceService
  ) { }

  async ngOnInit() {
    sessionStorage.setItem('clearInterval', 'true');
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      knowques: false,
      knowresult: false,
      CATresult: false,
      CATQue: false,
      studentprofile: false,
      PracticeResult: false,
      Practiceques: false,
      resource: false,
      liveSupport: true,
    };
    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;
      }
    }
    await this.getPaymentTranction();
    await this.getEventRecording();
    await this.getNextLiveCall();
  }
  resetTimer() {
    this.showControls = true;
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.hideControls();
    }, 3000);
  }

  hideControls() {
    this.showControls = false;
  }
  tabExpand() {
    document
      .getElementById('tabExpandOpen')
      .classList.toggle('tabExpandActive');
    document
      .getElementById('tabSection')
      .classList.toggle('history-main-tab-open');
  }
  matpaginator() {
    const note = document.querySelector('.mat-select-panel') as HTMLElement;
    note.style.backgroundColor = 'yellow';
  }
  async getEventRecording() {
    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
        this.spinner.show();
        var cohort_id = localStorage.getItem('cohort_id');
        var course_type = localStorage.getItem('course_type');
        var method = localStorage.getItem('method');
        if (method == '0') {
          course_type = 'live';
        }
        let request = {
          cohort_id: cohort_id,
          method_type: course_type,
        };
        await this.videoService
          .getEventRecording(request, token)
          .then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              var users: supportList[] = [];
              list.data.forEach((element) => {
                let play_list = element.play_list;
                let src_list = [];
                if (play_list) {
                  let play = JSON.parse(play_list);
                  if (play.length > 0) {
                    src_list = play;
                  }
                }
                if (src_list.length > 0) {
                  src_list.forEach((src) => {
                    src.src = element.meeting_id + '/audio/' + src.src;
                  });
                }
                if (element.recording_url != null) {
                  users.push({
                    certi_id: element.certi_id,
                    duration: element.duration,
                    event_id: element.event_id,
                    id: element.id,
                    meeting_id: element.meeting_id,
                    play_list: src_list,
                    title: element.title,
                    createdAt: element.createdAt,
                    recording_url: element.recording_url,
                    questions: JSON.parse(element.questions)
                  });
                }
              });
              this.recordingsData = users.reverse();
              this.dataSource = new MatTableDataSource(users);
              this.dataSource.paginator = this.paginator;
              this.pagination = true;
            }
          });

        this.spinner.hide();
      }
    });
  }

  async getPaymentTranction() {
    this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        this.spinner.show();
        var cohort_id = localStorage.getItem('cohort_id');
        var user_id = localStorage.getItem('CisspUserId');
        var userdetails = JSON.parse(localStorage.getItem('userdetails'));
        var email = userdetails.email

        await this.service
          .getPaymentTranction(email, user_id, cohort_id, token)
          .then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json).data;
              var productPurchase = list[0].product_purchased;
              this.userAmount = list[0].amount;
              var course_type = localStorage.getItem('course_type');
              var method_id = localStorage.getItem('method');
              if (course_type != '' && course_type != null && course_type != 'hybrid' && method_id != '0' && (Number(this.userAmount) > 997 || productPurchase == 'CISSP Preferred MasterClass' || productPurchase == 'CISSP Premier MasterClass')) {
                if (this.userAmount == "Enroll by admin") {
                  this.premierMasterClass = false;
                  this.noOfWay = "two"
                } else {
                  this.premierMasterClass = true;
                  this.noOfWay = "three"
                }
              } else {
                this.premierMasterClass = false;
                this.noOfWay = "two"
              }
            }
          })
        this.spinner.hide();
      }
    });
  }

  groupByArray(array, key) {
    return array.reduce((hash, obj) => {
      if (obj[key] === undefined) return hash;
      return Object.assign(hash, {
        [obj[key]]: (hash[obj[key]] || []).concat(obj),
      });
    }, {});
  }
  async getNextLiveCall() {
    this.spinner.show();
    this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        this.spinner.show();
        var cohort_id = localStorage.getItem('cohort_id');
        var user_id = localStorage.getItem('CisspUserId');
        await this.service
          .getNextLiveCall(cohort_id, user_id, token)
          .then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              let schedule_data = list.data;
              schedule_data.sort(
                (a, b) =>
                  new Date(a.due_date).getTime() -
                  new Date(b.due_date).getTime()
              );
              let running = schedule_data.filter(
                (x) => x.is_live == 1 && x.event_url != '#' && x.event_url != ''
              );
              if (running.length > 0) {
                this.showJoinButton = true;
                this.nextLiveCall = running[0];
                let timeZone = running[0].due_date.substr(
                  running[0].due_date.length - 6,
                  6
                );
                let due_date: Date;
                let currTimeZone = this.auth.currentTimeZone();
                if (currTimeZone.timeValue == timeZone) {
                  due_date = new Date(running[0].due_date);
                } else {
                  due_date = new Date(
                    new Date(running[0].due_date).toLocaleString('en-US', {
                      timeZone: this.timezone.nameValue,
                    })
                  );
                }
                this.nextLiveCall['due_date'] = due_date;
                this.nextLiveCall['ev_date'] =
                  this.dayNames[due_date.getDay()] +
                  ' ' +
                  this.monthsNames[due_date.getMonth()] +
                  ' ' +
                  due_date.getDate() +
                  ' at ' +
                  due_date.toLocaleTimeString('en-US', {
                    hour: 'numeric',
                    minute: 'numeric',
                    hour12: true,
                  }) +
                  ' ' +
                  this.timezone.abbr;
              } else {
                for (let i = 0; i < schedule_data.length; i++) {
                  schedule_data[i]['end_date'] =
                    schedule_data[i].due_date.toString().substr(0, 11) +
                    schedule_data[i].end_time +
                    schedule_data[i].due_date
                      .toString()
                      .substr(16, schedule_data[i].due_date.length);
                  let timeZone = schedule_data[i].due_date.substr(
                    schedule_data[i].due_date.length - 6,
                    6
                  );
                  let due_date: Date;
                  let end_date: Date;
                  let overdue_date;
                  let currTimeZone = this.auth.currentTimeZone();

                  due_date = new Date(
                    new Date(schedule_data[i].due_date).toLocaleString(
                      'en-US',
                      { timeZone: this.timezone.nameValue }
                    )
                  );

                  end_date = new Date(
                    new Date(schedule_data[i].end_date).toLocaleString(
                      'en-US',
                      { timeZone: this.timezone.nameValue }
                    )
                  );
                  let due =
                    schedule_data[i].due_date.split('T')[0] +
                    'T' +
                    schedule_data[i].end_time +
                    ':' +
                    schedule_data[i].due_date.split(':')[2] +
                    schedule_data[i].due_date.split(':')[3];
                  overdue_date = new Date(
                    new Date(due).toLocaleString('en-US', {
                      timeZone: this.timezone.nameValue,
                    })
                  );
                  let curr_date = new Date(
                    new Date().toLocaleString('en-US', {
                      timeZone: this.timezone.nameValue,
                    })
                  );
                  if (overdue_date.getTime() >= curr_date.getTime()) {
                    if (schedule_data[i].is_live == 1) {
                      this.showJoinButton = true;
                      this.isBefore15 = false;
                      this.nextLiveCall = schedule_data[i];
                      this.nextLiveCall['due_date'] = due_date;
                      this.nextLiveCall['end_date'] = end_date;
                      let dt = new Date(this.nextLiveCall.due_date);
                      this.nextLiveCall['ev_date'] =
                        this.dayNames[dt.getDay()] +
                        ' ' +
                        this.monthsNames[dt.getMonth()] +
                        ' ' +
                        dt.getDate() +
                        ' at ' +
                        dt.toLocaleTimeString('en-US', {
                          hour: 'numeric',
                          minute: 'numeric',
                          hour12: true,
                        }) +
                        ' ' +
                        this.timezone.abbr;
                    } else {
                      let before15Date = new Date(
                        new Date(due_date).setMinutes(
                          new Date(due_date).getMinutes() - 15
                        )
                      );
                      if (before15Date <= curr_date) {
                        this.isBefore15 = true;
                        this.showJoinButton = true;
                        this.nextLiveCall = schedule_data[i];
                        this.nextLiveCall['due_date'] = due_date;
                        this.nextLiveCall['end_date'] = end_date;
                        let dt = new Date(this.nextLiveCall.due_date);
                        this.nextLiveCall['ev_date'] =
                          this.dayNames[dt.getDay()] +
                          ' ' +
                          this.monthsNames[dt.getMonth()] +
                          ' ' +
                          dt.getDate() +
                          ' at ' +
                          dt.toLocaleTimeString('en-US', {
                            hour: 'numeric',
                            minute: 'numeric',
                            hour12: true,
                          }) +
                          ' ' +
                          this.timezone.abbr;
                      } else {
                        this.isBefore15 = false;
                        this.showJoinButton = false;
                        this.nextLiveCall = schedule_data[i];
                        this.nextLiveCall['due_date'] = due_date;
                        this.nextLiveCall['end_date'] = end_date;
                        let dt = new Date(this.nextLiveCall.due_date);
                        this.nextLiveCall['ev_date'] =
                          this.dayNames[dt.getDay()] +
                          ' ' +
                          this.monthsNames[dt.getMonth()] +
                          ' ' +
                          dt.getDate() +
                          ' at ' +
                          dt.toLocaleTimeString('en-US', {
                            hour: 'numeric',
                            minute: 'numeric',
                            hour12: true,
                          }) +
                          ' ' +
                          this.timezone.abbr;
                      }
                    }
                    break;
                  }
                }
              }
              if (this.nextLiveCall == null || this.nextLiveCall == undefined) {
                this.noEvent = true;
              } else {
                this.noEvent = false;
              }
            }
          });

        this.spinner.hide();
      }
    });
  }
  playVideoPopup(item: any) {
    var eventinfo = btoa(JSON.stringify(item.event_id));
    this.router.navigate([`/eventrecordings/${eventinfo}`]);
  }
  closeVideoPopup() {
    this.openVideoPopup = false;
    let overflow = document.getElementsByClassName("contentaarea")[0] as HTMLElement
    overflow.removeAttribute('style')
  }
  backwordvideo() {
    const video = document.getElementsByTagName('video');
    video[0].currentTime = video[0].currentTime - 10;
  }
  forwordvideo() {
    const video = document.getElementsByTagName('video');
    video[0].currentTime = video[0].currentTime + 10;
  }
  changeplay() {
    if (this.api.state == 'paused') this.api.play();
    if (this.api.state == 'playing') this.api.pause();
  }
  onPlayerReady(api: VgApiService) {
    this.api = api;
    this.playback = this.api.playbackRate;
    let me = this
    document.onkeydown = function (event) {
      const video = document.getElementsByTagName('video');
      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
          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
          break;
        case 190://>- Speedup video playback rate
          video[0].playbackRate += 0.25
          break;

      }
    };
    this.api
      .getDefaultMedia()
      .subscriptions.loadedMetadata.subscribe(this.playVideo.bind(this));
    this.api
      .getDefaultMedia()
      .subscriptions.ended.subscribe(this.nextVideo.bind(this));
  }
  playVideo() {
    this.api.play();
  }
  nextVideo() {
    this.currentIndex++;
    if (this.currentIndex === this.playList.length) {
      this.currentIndex = 0;
    }
    this.currentItem = this.playList[this.currentIndex];
  }
  calendar(type) {
    let data = JSON.parse(this.nextLiveCall.repeat_on);
    let weekdays = data
      .filter((item) => item.value === 1)
      .map((item) => {
        const dayName = item.name.slice(0, 2).toUpperCase();
        return dayName;
      });

    let options: CalendarOptions;
    if (this.nextLiveCall.repeat_type == 'Week') {
      if (this.nextLiveCall.ends_type == 'Never') {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            weekdays: weekdays,
          },
        };
      } else {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            weekdays: weekdays,
            end: new Date(this.nextLiveCall.ends_on),
          },
        };
      }
    } else if (
      this.nextLiveCall.repeat_type == '' ||
      this.nextLiveCall.repeat_type == null
    ) {
      options = {
        title: this.nextLiveCall.examname,
        description: this.nextLiveCall.examname,
        start: new Date(this.nextLiveCall.due_date),
        end: new Date(this.nextLiveCall.end_date),
      };
    } else {
      if (this.nextLiveCall.ends_type == 'Never') {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
          },
        };
      } else if (this.nextLiveCall.ends_type == 'After') {
        let end_on = new Date(this.nextLiveCall.ends_on);
        end_on.setDate(end_on.getDate() + 1);
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            end: new Date(end_on),
          },
        };
      } else {
        options = {
          title: this.nextLiveCall.examname,
          description: this.nextLiveCall.examname,
          start: new Date(this.nextLiveCall.due_date),
          end: new Date(this.nextLiveCall.end_date),
          recurrence: {
            frequency:
              this.nextLiveCall.repeat_type == 'Day'
                ? 'DAILY'
                : this.nextLiveCall.repeat_type == 'Week'
                  ? 'WEEKLY'
                  : this.nextLiveCall.repeat_type == 'Month'
                    ? 'MONTHLY'
                    : 'YEARLY',
            interval: this.nextLiveCall.repeat_count,
            end: new Date(this.nextLiveCall.ends_on),
          },
        };
      }
    }
    if (type == 'g') {
      const googleCalendar = new GoogleCalendar(options);
      window.open(googleCalendar.render());
    }
    if (type == 'o') {
      if (this.nextLiveCall.repeat_count == 0) {
        const outlookcalendar = new OutlookCalendar(options);
        window.open(outlookcalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(this.nextLiveCall.examname + '.ics');
      }
    }
    if (type == 'y') {
      if (this.nextLiveCall.repeat_count == 0) {
        const yahoocalendar = new YahooCalendar(options);
        window.open(yahoocalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(this.nextLiveCall.examname + '.ics');
      }
    }
    if (type == 'o3') {
      if (this.nextLiveCall.repeat_count == 0) {
        const outlookcalendar = new OutlookCalendar(options);
        window.open(outlookcalendar.render());
      } else {
        const icalendar = new ICalendar(options);
        icalendar.download(this.nextLiveCall.examname + '.ics');
      }
    }
    if (type == 'i') {
      const icalendar = new ICalendar(options);
      icalendar.download(this.nextLiveCall.examname + '.ics');
    }
  }
  popupCloseSM() {
    var element = document.getElementById('popup-close');
    element.classList.toggle('popup-opencal-open');
  }
  formatZone(zone: string): TZone {
    const utc: string = momentZone.tz(zone).format('Z');
    const abbr: string = momentZone.tz(zone).zoneAbbr();
    return {
      name: `${zone} (${utc})`,
      nameValue: zone,
      timeValue: utc,
      group: zone.split('/', 1)[0],
      abbr: abbr,
    };
  }
  joinMeeting() {
    if(!this.nextLiveCall.event_url){
      var eventstart = {
        id: this.nextLiveCall.id,
        title: this.nextLiveCall.examname,
        user_id: localStorage.getItem('CisspUserId'),
      };
      let meet_url = btoa(JSON.stringify(eventstart));
      meet_url = encodeURIComponent(meet_url);
      this.router.navigate([`startconference/${meet_url}`]);
    }else{
      window.open(this.nextLiveCall.event_url, '_blank');
    }
  }
}
export interface supportList {
  certi_id: number;
  duration: string;
  event_id: string;
  id: string;
  meeting_id: string;
  play_list: any;
  title: string;
  createdAt: string;
  recording_url: string;
  questions: any;
}
