import { Component, OnInit } from '@angular/core';
import { ServicesService } from 'src/app/services.service';
import { AuthserviceService } from '../../authservice.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { Router, ActivatedRoute } from '@angular/router';
import { VgApiService } from '@videogular/ngx-videogular/core';
import { VideoserviceService } from 'src/app/services/video/videoservice.service';
import { NotificationService } from 'src/app/services/notification/notification.service';
import * as momentZone from 'moment-timezone';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-notification',
  templateUrl: './notification.component.html',
  styleUrls: ['./notification.component.scss'],
})
export class NotificationComponent implements OnInit {
  constructor(
    public sanitizer: DomSanitizer,
    public service: ServicesService,
    public auth: AuthserviceService,
    public spinner: NgxSpinnerService,
    private route: ActivatedRoute,
    public router: Router,
    public notificationService: NotificationService,
    public videoService: VideoserviceService
  ) { }
  AllNotifications = [];
  bkpAllNotifications = [];
  selectedButton: boolean = false;
  Search = '';
  api: VgApiService;
  playList = [];
  currentIndex = 0;
  currentItem: any;
  recordingsData = [];
  playback: any;
  defaultPath: string =
    'https://recordings-new.s3.us-east-2.amazonaws.com/captures/';
  timezone: any = JSON.parse(<string>localStorage.getItem('userdetails'))
    .user_time_zone
    ? JSON.parse(
      JSON.parse(<string>localStorage.getItem('userdetails')).user_time_zone
    ).nameValue
    : this.auth.formatZone(momentZone.tz.guess(true)).nameValue;
  currentsorting: any = {
    clicktype: 'notice',
    sort: 'none',
    icon: '../../../assets/images/switch_right_black_default-2.png',
  };
  defaultIcon: any = '../../../assets/images/switch_right_black_default-2.png';
  sortIcon: any = '../../../assets/images/switch_right_black_24dp.svg';
  ngOnInit(): void {
    sessionStorage.setItem('clearInterval', 'true')
    this.getAllNotifications();
    this.getEventRecording();
    this.service.headershow = true;
    this.service.SearchValue = true;
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      CATresult: false,
      CATQue: false,
      PracticeResult: false,
      Practiceques: false,
      studentprofile: false,
      knowques: false,
      knowresult: false,
      resource: false,
      liveSupport: false,
    };
    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;
      }
    }
  }
  filterNotification(type) {
    this.selectedButton = type;
    this.AllNotifications = this.bkpAllNotifications.filter(
      (x) => x.is_read == type
    );
  }
  filter() {
    this.AllNotifications = this.bkpAllNotifications.filter((str) => {
      return str.message.toLowerCase().indexOf(this.Search.toLowerCase()) >= 0;
    });
  }

  async getAllNotifications() {
    this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        let user_id = localStorage.getItem('CisspUserId');
        let cohort_id = localStorage.getItem('cohort_id');
        this.spinner.show();
        let fire_time = this.auth.convertStringUtcTimeZone(
          this.auth.ConvertFormatDbDateTime(new Date(), this.timezone),
          this.timezone
        );
        await this.notificationService
          .getAllNotification(user_id, cohort_id, fire_time, token)
          .then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              this.AllNotifications = list.data;
              this.bkpAllNotifications = list.data;

              this.AllNotifications.forEach((element) => {
                if (element.message) {
                  element.fire_time =
                    this.auth.ConvertDateDDFormat(
                      element.meeting_date,
                      this.timezone,
                      'DD-MM-YYYY'
                    ) +
                    ' at ' +
                    this.auth.ConvertDateDDFormat(
                      element.meeting_date,
                      this.timezone,
                      'hh:mm A'
                    );
                  if (element.message.includes('by clicking button')) {
                    element['showmessage'] =
                      this.sanitizer.bypassSecurityTrustHtml(
                        element.message.split('by clicking button')[0]
                      );
                  } else if (
                    element.message.includes('will start from <a ><span')
                  ) {
                    element['showmessage'] =
                      this.sanitizer.bypassSecurityTrustHtml(
                        element.message.split('<a ><span')[0] +
                        this.auth.ConvertDateDDFormat(
                          element.meeting_date,
                          this.timezone,
                          'DD-MM-YYYY'
                        )
                      );
                  } else {
                    if (element.message.includes('will start from <a href=')) {
                      element['showmessage'] = element.message.replace(
                        'Join',
                        ''
                      );
                    } else {
                      element['showmessage'] =
                        this.sanitizer.bypassSecurityTrustHtml(element.message);
                    }
                  }
                  if (element.test_type == "meeting") {
                    const currentDate = new Date().getTime();
                    let meetingEndDate
                    if (typeof element.meeting_time_zone !== 'undefined') {
                      meetingEndDate =
                        element.meeting_date.toString().substr(0, 11) +
                        element.end_time +
                        ':00' +
                        JSON.parse(element.meeting_time_zone).timeValue;
                    }
                    const givenEndDate = new Date(meetingEndDate).getTime();
                    if (element.message.indexOf('https') > 0 && currentDate < givenEndDate) {
                      element['enable_btn'] = true;
                    } else {
                      element['enable_btn'] = false;
                    }
                  }
                } else {
                  element['showmessage'] =
                    this.sanitizer.bypassSecurityTrustHtml(element.message);
                }
              });
              this.spinner.hide();
            } else {
              this.spinner.hide();
            }
          });
      }
    });
  }
  async markAllRead() {
    this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        let user_id = localStorage.getItem('CisspUserId');
        let cohort_id = localStorage.getItem('cohort_id');
        let fire_time = this.auth.ConvertDateDDFormat(
          new Date(),
          Intl.DateTimeFormat().resolvedOptions().timeZone,
          'YYYY-MM-DD HH:mm:SS'
        );
        await this.notificationService
          .markReadPopupNotification(user_id, cohort_id, fire_time, token)
          .then(async (data) => {
            if (data[0].status == 200) {
              this.service.ShowSuccess('Read all notifications successfully');
              await this.getAllNotifications();
              this.spinner.hide();
            } else {
              this.spinner.hide();
            }
          });
      }
    });
  }
  Join(item) {
    var eventstart = {
      id: item.test_id,
      title: '',
      user_id: localStorage.getItem('CisspUserId'),
    };
    let meet_url = btoa(JSON.stringify(eventstart));
    meet_url = encodeURIComponent(meet_url);
    this.router.navigate([`startconference/${meet_url}`]);
  }
  startExam(item) {
    if (item.test_type == 'PRACTICE') {
      this.router.navigate(['/sidenav/practicetest']);
    }
    if (item.test_type == 'CAT') {
      this.router.navigate(['/sidenav/cateexamtest']);
    }
    if (item.test_type == 'KA') {
      this.router.navigate(['/sidenav/knowledge']);
    }
    if (item.test_type == 'MESSAGE') {
      this.router.navigate(['/sidenav/chatting']);
    }
  }
  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);
              const 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;
                  });
                }
                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,
                });
              });

              this.recordingsData = users;
            }
          });

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

  playVideoPopup(item: any) {
    var eventinfo = btoa(JSON.stringify(item.test_id));
    this.router.navigate([`/eventrecordings/${eventinfo}`]);
  }

  SortingNotification(sortType: any) {
    if (this.currentsorting.clicktype != sortType) {
      this.currentsorting.icon = this.sortIcon;
      this.currentsorting.sort = 'asc';
    } else {
      if (this.currentsorting.sort == 'desc') {
        this.currentsorting.icon = this.defaultIcon;
        this.currentsorting.sort = 'none';
      } else if (this.currentsorting.sort == 'asc') {
        this.currentsorting.icon = this.sortIcon;
        this.currentsorting.sort = 'desc';
      } else {
        this.currentsorting.icon = this.sortIcon;
        this.currentsorting.sort = 'asc';
      }
    }
    this.currentsorting.clicktype = sortType;
    if (sortType == 'notice') {
      if (this.currentsorting.sort == 'asc') {
        this.AllNotifications.sort(function (a, b) {
          if (a.showmessage.toLowerCase() < b.showmessage.toLowerCase()) {
            return -1;
          }
          if (a.showmessage.toLowerCase() > b.showmessage.toLowerCase()) {
            return 1;
          }
          return 0;
        });
      } else if (this.currentsorting.sort == 'desc') {
        this.AllNotifications.sort(function (a, b) {
          if (b.showmessage.toLowerCase() < a.showmessage.toLowerCase()) {
            return -1;
          }
          if (b.showmessage.toLowerCase() > a.showmessage.toLowerCase()) {
            return 1;
          }
          return 0;
        });
      } else {
        this.AllNotifications = this.bkpAllNotifications;
      }
    } else if (sortType == 'type') {
      if (this.currentsorting.sort == 'asc') {
        this.AllNotifications.sort(function (a, b) {
          if (a.test_type.toLowerCase() < b.test_type.toLowerCase()) {
            return -1;
          }
          if (a.test_type.toLowerCase() > b.test_type.toLowerCase()) {
            return 1;
          }
          return 0;
        });
      } else if (this.currentsorting.sort == 'desc') {
        this.AllNotifications.sort(function (a, b) {
          if (b.test_type.toLowerCase() < a.test_type.toLowerCase()) {
            return -1;
          }
          if (b.test_type.toLowerCase() > a.test_type.toLowerCase()) {
            return 1;
          }
          return 0;
        });
      } else {
        this.AllNotifications = this.bkpAllNotifications;
      }
    } else if (sortType == 'date') {
      if (this.currentsorting.sort == 'asc') {
        this.AllNotifications.sort(function (a, b) {
          return (
            new Date(a.meeting_date).getTime() -
            new Date(b.meeting_date).getTime()
          );
        });
      } else if (this.currentsorting.sort == 'desc') {
        this.AllNotifications.sort(function (a, b) {
          return (
            new Date(b.meeting_date).getTime() -
            new Date(a.meeting_date).getTime()
          );
        });
      } else {
        this.AllNotifications = this.bkpAllNotifications;
      }
    }
  }
}
export interface supportList {
  certi_id: number;
  duration: string;
  event_id: string;
  id: string;
  meeting_id: string;
  play_list: any;
  title: string;
}
