import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ServicesService } from 'src/app/services.service';
import {
  ConsoleLogger,
  DefaultAudioVideoController,
  DefaultDeviceController,
  DefaultMeetingSession,
  DefaultReconnectController,
  DefaultWebSocketAdapter,
  FullJitterBackoff,
  LogLevel,
  MeetingSessionConfiguration,
} from 'amazon-chime-sdk-js';
// import * as Chime from 'aws-sdk/clients/chime';
import { ActivatedRoute, Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import Swal from 'sweetalert2/dist/sweetalert2.js';
import { AuthserviceService } from 'src/app/authservice.service';
import { ChattingService } from 'src/app/services/chatting/chatting.service';
import { Location } from '@angular/common';
declare const JitsiMeetExternalAPI: any;

@Component({
  selector: 'app-conference',
  templateUrl: './conference.component.html',
  styleUrls: ['./conference.component.scss'],
})
export class ConferenceComponent implements OnInit, AfterViewInit{
  private meetingInstance: any;
  @ViewChild('jitsiContainer', { static: true }) jitsiContainer: ElementRef;
  MeetingResponse = {
    meeting: {
      Meeting: {
        MeetingId: 'd3fb6e1e-2876-4bcc-aa14-860d57620706',
        ExternalMeetingId: '33f3f459-6840-41e5-83ac-d8c2302ff61f',
        MediaPlacement: {
          AudioHostUrl:
            '4e6deb0b8b66f4a6b7ea8d291eca1d09.k.m1.ue1.app.chime.aws:3478',
          AudioFallbackUrl:
            'wss://haxrp.m1.ue1.app.chime.aws:443/calls/d3fb6e1e-2876-4bcc-aa14-860d57620706',
          ScreenDataUrl:
            'wss://bitpw.m1.ue1.app.chime.aws:443/v2/screen/d3fb6e1e-2876-4bcc-aa14-860d57620706',
          ScreenSharingUrl:
            'wss://bitpw.m1.ue1.app.chime.aws:443/v2/screen/d3fb6e1e-2876-4bcc-aa14-860d57620706',
          ScreenViewingUrl:
            'wss://bitpw.m1.ue1.app.chime.aws:443/ws/connect?passcode=null&viewer_uuid=null&X-BitHub-Call-Id=d3fb6e1e-2876-4bcc-aa14-860d57620706',
          SignalingUrl:
            'wss://signal.m1.ue1.app.chime.aws/control/d3fb6e1e-2876-4bcc-aa14-860d57620706',
          TurnControlUrl: 'https://ccp.cp.ue1.app.chime.aws/v2/turn_sessions',
        },
        MediaRegion: 'us-east-1',
      },
    },
    attendee: {
      Attendee: {
        ExternalUserId: '319c9264#2017',
        AttendeeId: '7f129f67-8a72-c9ad-fa73-68dcef4b3499',
        JoinToken:
          'N2YxMjlmNjctOGE3Mi1jOWFkLWZhNzMtNjhkY2VmNGIzNDk5OmY3OGMwNDE3LTY2NmYtNGQ5NS1hY2U4LTIwNWE0Y2YyM2NlZQ',
      },
    },
  };
  meetingSession: DefaultMeetingSession;
  IsMuted: boolean = false;
  IsFullScreen: boolean = false;
  ShowAttendees: boolean = true;
  ShowChat: boolean = false;
  cohort_id: any;
  db_meeting_id: any;
  TempMessages = [];
  Messages = [];
  message = '';
  toggled: boolean = false;
  // chime = new Chime({ region: 'us-east-1' });
  Attendees = [];
  AttendeesCount = 0;
  MeetingName: any;
  AdminUserId: any;
  AdminAttendeeId: any;
  MyAttendeeId: any;
  MyExternalAttendeeId: any;
  toggledView: boolean = false;
  muteByPresenter: boolean = false;
  IsStartVideo: boolean = false;
  selectedAudio = '';
  selectedVideo = '';
  chooseDevicePopup: boolean = false;
  audioDevices = [];
  videoDevices = [];
  isMeetingVisible = false;
  constructor(
    private location: Location,
    public chatService: ChattingService,
    public auth: AuthserviceService,
    public router: Router,
    public service: ServicesService,
    public ActiveRoute: ActivatedRoute,
    public spinner: NgxSpinnerService
  ) {
    this.ActiveRoute.params.subscribe(async (params) => {
      try {
        var data = JSON.parse(atob(decodeURIComponent(params['id'])));
        debugger;
        this.MyAttendeeId = data.AttendeeId;
        this.MeetingName = data.title;
        await this.getMeetingById(data.meeting_id, data.AttendeeId);
      } catch (error) {
      }
    });
  }
  ngOnInit(): void {
    // setTimeout(() => {
    //   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;
    //     }
    //   }
    // }, 100);
    // this.spinner.show();
    // this.toggledView = true;
    // this.spinner.hide();
  }
  back() {
    this.location.back();
  }
  ngAfterViewInit(){
    this.meetingStart();
    this.spinner.hide();
  }
  meetingStart(){
    let userdetails = JSON.parse(localStorage.getItem('userdetails'));
    let name = userdetails.aliasname
      ? userdetails.aliasname
      : userdetails.name
        ? userdetails.name
        : userdetails.email;
    const options = {
      roomName: this.MeetingName,
      userInfo: {
        displayName: name
      },
      configOverwrite: {
        disableDeepLinking: true
      },
      parentNode: document.querySelector('#jitsiContainer'),
      interfaceConfigOverwrite: { DEFAULT_BACKGROUND: "#fff", SHOW_JITSI_WATERMARK: false, DEFAULT_REMOTE_DISPLAY_NAME: 'Flexxon',
      DEFAULT_LOCAL_DISPLAY_NAME: 'Flexxon', SHOW_WATERMARK_FOR_GUESTS: false, SHOW_BRAND_WATERMARK: false, TOOLBAR_BUTTONS: [
        'microphone', 'camera', 'desktop', 'fullscreen',
        'fodeviceselection', , 'profile', 'chat',
        'settings', 'raisehand',
        'videoquality', 'filmstrip', 'stats',
        'tileview'
      ]},
    };

    this.meetingInstance = new (window as any).JitsiMeetExternalAPI("meet.jit.si", options);
    this.isMeetingVisible = true;
    this.meetingInstance.addEventListener("videoConferenceJoined", () => {
      // this.meetingInstance.executeCommand("displayName", this.meetingInstance.getParticipantsInfo()[0].displayName);
      this.meetingInstance.executeCommand("displayName", name);
      this.meetingInstance.executeCommand('toggleCamera');
      this.meetingInstance.executeCommand('toggleAudio');
      this.meetingInstance.executeCommand('toggleVideo');
    });
    this.meetingInstance.addListener('participantJoined', this.handleParticipantJoined);
    this.meetingInstance.addListener('readyToClose', this.handleDisconnect.bind(this));
    // this.meetingInstance.addListener('audioMuteStatusChanged', this.handleAudioMuteStatusChanged.bind(this));
    this.meetingInstance.addEventListener("videoConferenceLeft", () => {
      this.meetingInstance.dispose();
      this.router.navigate([`sidenav/dashboard`]);
    });
    // console.log('this.meetingInstance------------------------>', this.meetingInstance)
  }
  handleParticipantJoined(participant: { id: string, displayName: string }): void {
    // console.log('Participant joined:---------------------------------------->', participant);
  }
  handleDisconnect = () => {
    alert ('going to close');
    this.isMeetingVisible = false;
    this.meetingInstance.executeCommand('endConference');
    this.meetingInstance.dispose();
    this.router.navigate([`sidenav/dashboard`]);
  }
  closemeeting(){
    this.isMeetingVisible = false;
    this.meetingInstance.executeCommand('endConference'); //endconference by admin
    this.meetingInstance.dispose();
    this.router.navigate([`sidenav/dashboard`]);
  }
  async getMeetingById(id, AttendeeId) {
    this.spinner.show();
    var token = '';
    await this.chatService
      .getMeetingById(id, token)
      .then(async (result) => {
        let my_user_id = localStorage.getItem('CisspUserId');
        var list = JSON.parse(<string>result[0].json);
        if (result[0].status == 200) {
          this.MeetingName = list.data.event_name;
          this.AdminUserId = list.data.created_by;
          this.AdminAttendeeId = list.data.admin_attendee_id;
          let att = JSON.parse(list.data.attendees);
          let myAtt = att.filter((x) => x.U == my_user_id);
          this.MyExternalAttendeeId = myAtt[0].A;
          let attendees = '';
          att.forEach((element) => {
            attendees = attendees + element.U + ',';
          });
          // if (attendees.endsWith(',') == true) {
          //   attendees = attendees.substring(0, attendees.length - 1);
          // }
          // this.cohort_id = list.data.cohort_id;
          // this.db_meeting_id = list.data.id;
          // await this.getAttendeeDetails(attendees, att);
          // await this.getMeeting(AttendeeId, list.data.meeting_id);
          // await this.getMessage(list.data.id, 0);
        }
        this.spinner.hide();
      });
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   } else {
    //     var token = session
    //     await this.chatService
    //       .getMeetingById(id, token)
    //       .then(async (result) => {
    //         let my_user_id = localStorage.getItem('CisspUserId');
    //         var list = JSON.parse(<string>result[0].json);
    //         if (result[0].status == 200) {
    //           this.MeetingName = list.data.event_name;
    //           this.AdminUserId = list.data.created_by;
    //           this.AdminAttendeeId = list.data.admin_attendee_id;
    //           let att = JSON.parse(list.data.attendees);
    //           let myAtt = att.filter((x) => x.U == my_user_id);
    //           this.MyExternalAttendeeId = myAtt[0].A;
    //           let attendees = '';
    //           att.forEach((element) => {
    //             attendees = attendees + element.U + ',';
    //           });
    //           if (attendees.endsWith(',') == true) {
    //             attendees = attendees.substring(0, attendees.length - 1);
    //           }
    //           this.cohort_id = list.data.cohort_id;
    //           this.db_meeting_id = list.data.id;
    //           await this.getAttendeeDetails(attendees, att);
    //           await this.getMeeting(AttendeeId, list.data.meeting_id);
    //           await this.getMessage(list.data.id, 0);
    //         }
    //         this.spinner.hide();
    //       });
    //   }
    // });
  }
  // async getMeeting(AttendeeId, MeetingId) {
  //   this.spinner.show();
  //   await this.service
  //     .getMeeting(AttendeeId, MeetingId)
  //     .then(async (result) => {
  //       var list = JSON.parse(<string>result[0].json);
  //       if (list.status == 200) {
  //         this.MeetingResponse = list.data;
  //         await this.start();
  //         await this.saveLog('join');
  //         this.spinner.hide();
  //         this.service.ShowSuccess('Meeting has been join successfully');
  //       } else {
  //         this.service.ShowError('Meeting has been ended');
  //         this.spinner.hide();
  //         this.router.navigate(['sidenav/dashboard']);
  //       }
  //     });
  // }
  // async saveLog(status) {
  //   let user_id = localStorage.getItem('CisspUserId');
  //   let attendeeLog = [];
  //   var token = '';
  //   let userdetails = JSON.parse(localStorage.getItem('userdetails'));
  //   let name = userdetails.aliasname
  //     ? userdetails.aliasname
  //     : userdetails.name
  //       ? userdetails.name
  //       : userdetails.email;
  //   let message = name + ' has joined the meeting';
  //   if (status == 'left') {
  //     message = name + ' has left the meeting';
  //     attendeeLog = [
  //       {
  //         user_id: user_id,
  //         AttendeeId: this.MyExternalAttendeeId,
  //         status: 'Left',
  //       },
  //     ];
  //     this.Attendees.forEach((element) => {
  //       if (element.AttendeeId == this.MyExternalAttendeeId) {
  //         element.activeUser = false;
  //         this.AttendeesCount--;
  //       }
  //     });
  //   } else if (status == 'pause') {
  //     message = '';
  //     attendeeLog = [
  //       {
  //         user_id: user_id,
  //         AttendeeId: this.MyExternalAttendeeId,
  //         status: 'Pause',
  //       },
  //     ];
  //   } else if (status == 'play') {
  //     message = '';
  //     attendeeLog = [
  //       {
  //         user_id: user_id,
  //         AttendeeId: this.MyExternalAttendeeId,
  //         status: 'Play',
  //       },
  //     ];

  //   } 
  //   let atLog = attendeeLog.length > 0 ? JSON.stringify(attendeeLog) : '';
  //   let ref_number = this.generateRandom();
  //   await this.chatService
  //     .saveMessageConference(
  //       this.cohort_id,
  //       user_id,
  //       this.db_meeting_id,
  //       this.MeetingResponse.meeting.Meeting.MeetingId,
  //       'log',
  //       atLog,
  //       message,
  //       ref_number,
  //       token
  //     )
  //     .then(async (data) => {
  //       if (data[0].status == 200) {
  //         var list = JSON.parse(<string>data[0].json);
  //         this.meetingSession.audioVideo.realtimeSendDataMessage(
  //           this.MeetingResponse.meeting.Meeting.MeetingId,
  //           status
  //         );
  //         this.message = '';
  //       }
  //     });
  //   this.spinner.hide();
  //   // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
  //   //   if (err) {
  //   //     await this.spinner.hide();
  //   //     this.router.navigate(['/login']);
  //   //   } else {
  //   //     let attendeeLog = [];
  //   //     var token = session
  //   //     let userdetails = JSON.parse(localStorage.getItem('userdetails'));
  //   //     let name = userdetails.aliasname
  //   //       ? userdetails.aliasname
  //   //       : userdetails.name
  //   //         ? userdetails.name
  //   //         : userdetails.email;
  //   //     let message = name + ' has joined the meeting';
  //   //     if (status == 'left') {
  //   //       message = name + ' has left the meeting';
  //   //       attendeeLog = [
  //   //         {
  //   //           user_id: user_id,
  //   //           AttendeeId: this.MyExternalAttendeeId,
  //   //           status: 'Left',
  //   //         },
  //   //       ];
  //   //       this.Attendees.forEach((element) => {
  //   //         if (element.AttendeeId == this.MyExternalAttendeeId) {
  //   //           element.activeUser = false;
  //   //           this.AttendeesCount--;
  //   //         }
  //   //       });
  //   //     } else if (status == 'pause') {
  //   //       message = '';
  //   //       attendeeLog = [
  //   //         {
  //   //           user_id: user_id,
  //   //           AttendeeId: this.MyExternalAttendeeId,
  //   //           status: 'Pause',
  //   //         },
  //   //       ];
  //   //     } else if (status == 'play') {
  //   //       message = '';
  //   //       attendeeLog = [
  //   //         {
  //   //           user_id: user_id,
  //   //           AttendeeId: this.MyExternalAttendeeId,
  //   //           status: 'Play',
  //   //         },
  //   //       ];

  //   //     } 
  //   //     let atLog = attendeeLog.length > 0 ? JSON.stringify(attendeeLog) : '';
  //   //     let ref_number = this.generateRandom();
  //   //     await this.chatService
  //   //       .saveMessageConference(
  //   //         this.cohort_id,
  //   //         user_id,
  //   //         this.db_meeting_id,
  //   //         this.MeetingResponse.meeting.Meeting.MeetingId,
  //   //         'log',
  //   //         atLog,
  //   //         message,
  //   //         ref_number,
  //   //         token
  //   //       )
  //   //       .then(async (data) => {
  //   //         if (data[0].status == 200) {
  //   //           var list = JSON.parse(<string>data[0].json);
  //   //           this.meetingSession.audioVideo.realtimeSendDataMessage(
  //   //             this.MeetingResponse.meeting.Meeting.MeetingId,
  //   //             status
  //   //           );
  //   //           this.message = '';
  //   //         }
  //   //       });
  //   //     this.spinner.hide();
  //   //   }
  //   // });
  // }
  // async getAttendeeDetails(attendees, att) {
  //   this.spinner.show();
  //   var token = ''
  //   await this.chatService
  //     .getAllChannelUsers(attendees, token)
  //     .then(async (data) => {
  //       if (data[0].status == 200) {
  //         var list = JSON.parse(<string>data[0].json);
  //         this.Attendees = list.data;
  //         this.Attendees.forEach((element) => {
  //           element['activeUser'] = false;
  //           let atts = att.filter((x) => x.U == element.id);
  //           element['AttendeeId'] = atts[0].A;

  //           if (element.id == this.AdminUserId) {
  //             element['presenter'] = true;
  //             element['activeUser'] = true;
  //           } else {
  //             element['presenter'] = false;
  //           }
  //         });
  //         this.AttendeesCount = this.Attendees.filter(
  //           (x) => x.activeUser
  //         ).length;
  //       }
  //     });
  //   // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
  //   //   if (err) {
  //   //     await this.spinner.hide();
  //   //     this.router.navigate(['/login']);
  //   //   } else {
  //   //     var token = session
  //   //     await this.chatService
  //   //       .getAllChannelUsers(attendees, token)
  //   //       .then(async (data) => {
  //   //         if (data[0].status == 200) {
  //   //           var list = JSON.parse(<string>data[0].json);
  //   //           this.Attendees = list.data;
  //   //           this.Attendees.forEach((element) => {
  //   //             element['activeUser'] = false;
  //   //             let atts = att.filter((x) => x.U == element.id);
  //   //             element['AttendeeId'] = atts[0].A;

  //   //             if (element.id == this.AdminUserId) {
  //   //               element['presenter'] = true;
  //   //               element['activeUser'] = true;
  //   //             } else {
  //   //               element['presenter'] = false;
  //   //             }
  //   //           });
  //   //           this.AttendeesCount = this.Attendees.filter(
  //   //             (x) => x.activeUser
  //   //           ).length;
  //   //         }
  //   //       });
  //   //     this.spinner.hide();
  //   //   }
  //   // });
  //   this.spinner.hide();
  // }
  // async getMessage(meeting_id, limitRecord = 0) {
  //   var token = '';
  //   await this.chatService
  //     .getConferenceMessage(meeting_id, limitRecord, token)
  //     .then(async (data) => {
  //       if (data[0].status == 200) {
  //         var list = JSON.parse(<string>data[0].json);
  //         list.data = list.data.reverse();
  //         this.TempMessages.push(list.data);
  //         this.ChattingDetails();
  //       }
  //     });
  //   this.spinner.hide();
  //   // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
  //   //   if (err) {
  //   //     await this.spinner.hide();
  //   //     this.router.navigate(['/login']);
  //   //   } else {
  //   //     var token = session
  //   //     await this.chatService
  //   //       .getConferenceMessage(meeting_id, limitRecord, token)
  //   //       .then(async (data) => {
  //   //         if (data[0].status == 200) {
  //   //           var list = JSON.parse(<string>data[0].json);
  //   //           list.data = list.data.reverse();
  //   //           this.TempMessages.push(list.data);
  //   //           this.ChattingDetails();
  //   //         }
  //   //       });
  //   //     this.spinner.hide();
  //   //   }
  //   // });
  // }
  // public ChattingDetails() {
  //   let msg = [];
  //   for (const key in this.TempMessages) {
  //     this.TempMessages[key].forEach((element) => {
  //       msg.push(element);
  //     });
  //   }
  //   this.Messages = msg;
  //   this.Messages.forEach((el) => {
  //     el['mydate'] = el.createdAt.split('T')[0];
  //     if (el.user.id == this.AdminUserId) {
  //       el['color'] = '#f050ac';
  //     } else {
  //       el['color'] = '#8069c1';
  //     }
  //   });
  //   let grouping = [];
  //   let grouped = this.groupByDate(this.Messages, 'mydate');
  //   for (const key in grouped) {
  //     grouped[key].forEach((element) => {
  //       grouping.push(element);
  //     });
  //   }
  //   this.Messages = grouping;
  // }
  // groupByDate(array, key) {
  //   return array.reduce(function (rv, x) {
  //     (rv[x[key]] = rv[x[key]] || []).push(x);
  //     return rv;
  //   }, {});
  // }
  // generateRandom() {
  //   var chars =
  //     '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  //   let ids = '';
  //   for (let id = 0; id < 16; id++) {
  //     ids += chars[Math.floor(Math.random() * chars.length)];
  //   }
  //   return ids;
  // }
  // async sendMessage() {
  //   if (this.message && this.message.trim()) {
  //     this.meetingSession.audioVideo.realtimeSendDataMessage(
  //       this.MeetingResponse.meeting.Meeting.MeetingId,
  //       this.message
  //     );
  //     let ref_number = this.generateRandom();
  //     let user_id = localStorage.getItem('CisspUserId');
  //     let userdetails = JSON.parse(localStorage.getItem('userdetails'));
  //     let msg = {
  //       attendees_log: '',
  //       aws_meeting_id:
  //         this.Messages.length > 0 ? this.Messages[0].aws_meeting_id : '',
  //       cohort_id: null,
  //       color: '#f050ac',
  //       createdAt: new Date().toISOString(),
  //       emoji_count: [],
  //       id:
  //         this.Messages.length > 0
  //           ? this.Messages[this.Messages.length - 1].id + 1
  //           : 1,
  //       meeting_id: this.Messages.length > 0 ? this.Messages[0].meeting_id : '',
  //       message: this.message,
  //       message_type: 'text',
  //       mydate:
  //         new Date().getFullYear() +
  //         '-' +
  //         (new Date().getMonth() + 1) +
  //         '-' +
  //         new Date().getDate(),
  //       status: 0,
  //       updatedAt: new Date().toISOString(),
  //       user: {
  //         aliasname: userdetails.aliasname,
  //         avatar_url: userdetails.avatar_url,
  //         email: userdetails.email,
  //         id: user_id,
  //         name: userdetails.email.split('@')[0],
  //       },
  //       user_id: user_id,
  //       ref_number: ref_number,
  //     };
  //     var x = [];
  //     x.push(msg);
  //     let already = this.Messages.filter((x) => x.id == msg.id);
  //     if (already.length <= 0) {
  //       this.TempMessages.push(x);
  //       this.ChattingDetails();
  //     }
  //     x = [];
  //     let mmssgg = this.message;
  //     this.message = '';

  //     var token = '';
  //     await this.chatService
  //       .saveMessageConference(
  //         this.cohort_id,
  //         user_id,
  //         this.db_meeting_id,
  //         this.MeetingResponse.meeting.Meeting.MeetingId,
  //         'text',
  //         '',
  //         mmssgg,
  //         ref_number,
  //         token
  //       )
  //       .then(async (data) => {
  //         if (data[0].status == 200) {
  //           var list = JSON.parse(<string>data[0].json);
  //           this.message = '';
  //         }
  //       });
  //     this.spinner.hide();
  //     // await this.auth
  //     //   .getAuthenticatedUser()
  //     //   .getSession(async (err, session) => {
  //     //     if (err) {
  //     //       await this.spinner.hide();
  //     //       this.router.navigate(['/login']);
  //     //     } else {
  //     //       var token = session
  //     //       await this.chatService
  //     //         .saveMessageConference(
  //     //           this.cohort_id,
  //     //           user_id,
  //     //           this.db_meeting_id,
  //     //           this.MeetingResponse.meeting.Meeting.MeetingId,
  //     //           'text',
  //     //           '',
  //     //           mmssgg,
  //     //           ref_number,
  //     //           token
  //     //         )
  //     //         .then(async (data) => {
  //     //           if (data[0].status == 200) {
  //     //             var list = JSON.parse(<string>data[0].json);
  //     //             this.message = '';
  //     //           }
  //     //         });
  //     //       this.spinner.hide();
  //     //     }
  //     //   });
  //   }
  // }
  // onPickedEmoji(event) {
  //   this.message += event.char;
  // }
  // async getSingleMessage(db_meeting_id) {
  //   var token = ''
  //   await this.chatService
  //     .getSingleMessageConference(db_meeting_id, token)
  //     .then(async (data) => {
  //       if (data[0].status == 200) {
  //         var list = JSON.parse(<string>data[0].json);
  //         list.data = list.data.reverse();
  //         for (let i = 0; i < list.data.length; i++) {
  //           let already = this.Messages.filter(
  //             (x) => x.ref_number == list.data[i].ref_number
  //           );
  //           if (already.length <= 0) {
  //             let attendees_log = list.data[i].attendees_log
  //               ? JSON.parse(list.data[i].attendees_log)
  //               : [];
  //             if (attendees_log.length > 0) {
  //               let state = attendees_log[0].status;
  //               let attid = attendees_log[0].AttendeeId;
  //               if (attid == this.MyExternalAttendeeId) {
  //                 if (state == 'Mute') {
  //                   this.IsMuted = true;
  //                   this.meetingSession.audioVideo.realtimeMuteLocalAudio();
  //                   this.muteByPresenter = true;
  //                 } else if (state == 'Unmute') {
  //                   this.IsMuted = false;
  //                   this.meetingSession.audioVideo.realtimeUnmuteLocalAudio();
  //                   this.muteByPresenter = false;
  //                 }
  //               } else {
  //                 if (state == 'End') {
  //                   Swal.fire({
  //                     title: 'Leave Meeting?',
  //                     icon: 'warning',
  //                     showCancelButton: true,
  //                     confirmButtonColor: '#3085d6',
  //                     cancelButtonColor: '#d33',
  //                     confirmButtonText: 'Yes',
  //                   }).then(async (result) => {
  //                     if (result.value) {
  //                       if (this.meetingSession) {
  //                         this.meetingSession.audioVideo.stop();
  //                         this.meetingSession.audioVideo.chooseVideoInputDevice(
  //                           null
  //                         );
  //                         this.meetingSession.audioVideo.stopLocalVideoTile();
  //                       }
  //                       window.location.href = 'sidenav/dashboard';
  //                     }
  //                   });
  //                 }
  //               }
  //             }
  //             var x = [];
  //             x.push(list.data[i]);
  //             this.TempMessages.push(x);
  //             x = [];
  //             this.ChattingDetails();
  //           }
  //         }
  //       }
  //     });
  //   this.spinner.hide();
  //   // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
  //   //   if (err) {
  //   //     await this.spinner.hide();
  //   //     this.router.navigate(['/login']);
  //   //   } else {
  //   //     var token = session
  //   //     await this.chatService
  //   //       .getSingleMessageConference(db_meeting_id, token)
  //   //       .then(async (data) => {
  //   //         if (data[0].status == 200) {
  //   //           var list = JSON.parse(<string>data[0].json);
  //   //           list.data = list.data.reverse();
  //   //           for (let i = 0; i < list.data.length; i++) {
  //   //             let already = this.Messages.filter(
  //   //               (x) => x.ref_number == list.data[i].ref_number
  //   //             );
  //   //             if (already.length <= 0) {
  //   //               let attendees_log = list.data[i].attendees_log
  //   //                 ? JSON.parse(list.data[i].attendees_log)
  //   //                 : [];
  //   //               if (attendees_log.length > 0) {
  //   //                 let state = attendees_log[0].status;
  //   //                 let attid = attendees_log[0].AttendeeId;
  //   //                 if (attid == this.MyExternalAttendeeId) {
  //   //                   if (state == 'Mute') {
  //   //                     this.IsMuted = true;
  //   //                     this.meetingSession.audioVideo.realtimeMuteLocalAudio();
  //   //                     this.muteByPresenter = true;
  //   //                   } else if (state == 'Unmute') {
  //   //                     this.IsMuted = false;
  //   //                     this.meetingSession.audioVideo.realtimeUnmuteLocalAudio();
  //   //                     this.muteByPresenter = false;
  //   //                   }
  //   //                 } else {
  //   //                   if (state == 'End') {
  //   //                     Swal.fire({
  //   //                       title: 'Leave Meeting?',
  //   //                       icon: 'warning',
  //   //                       showCancelButton: true,
  //   //                       confirmButtonColor: '#3085d6',
  //   //                       cancelButtonColor: '#d33',
  //   //                       confirmButtonText: 'Yes',
  //   //                     }).then(async (result) => {
  //   //                       if (result.value) {
  //   //                         if (this.meetingSession) {
  //   //                           this.meetingSession.audioVideo.stop();
  //   //                           this.meetingSession.audioVideo.chooseVideoInputDevice(
  //   //                             null
  //   //                           );
  //   //                           this.meetingSession.audioVideo.stopLocalVideoTile();
  //   //                         }
  //   //                         window.location.href = 'sidenav/dashboard';
  //   //                       }
  //   //                     });
  //   //                   }
  //   //                 }
  //   //               }
  //   //               var x = [];
  //   //               x.push(list.data[i]);
  //   //               this.TempMessages.push(x);
  //   //               x = [];
  //   //               this.ChattingDetails();
  //   //             }
  //   //           }
  //   //         }
  //   //       });
  //   //     this.spinner.hide();
  //   //   }
  //   // });
  // }

  // async start() {
  //   try {
  //     const logger = new ConsoleLogger('SDK', LogLevel.OFF);
  //     const configuration = new MeetingSessionConfiguration(
  //       this.MeetingResponse.meeting.Meeting,
  //       this.MeetingResponse.attendee.Attendee
  //     );
  //     const deviceController = new DefaultDeviceController(logger);

  //     let audioVideoController = new DefaultAudioVideoController(
  //       configuration,
  //       logger,
  //       new DefaultWebSocketAdapter(logger),
  //       deviceController,
  //       new DefaultReconnectController(
  //         configuration.reconnectTimeoutMs,
  //         new FullJitterBackoff(
  //           configuration.reconnectFixedWaitMs,
  //           configuration.reconnectShortBackOffMs,
  //           configuration.reconnectLongBackOffMs
  //         )
  //       )
  //     );
  //     deviceController.bindToAudioVideoController(audioVideoController);
  //     this.meetingSession = new DefaultMeetingSession(
  //       configuration,
  //       logger,
  //       deviceController
  //     );
  //     this.changeAudioVideoSource();

  //     let me = this;
  //     const observer = {
  //       videoTileDidUpdate: (tileState) => {
  //         if (!tileState.boundAttendeeId) {
  //           return;
  //         }
  //         let attId = tileState.boundExternalUserId;
  //         me.Attendees.forEach((element) => {
  //           if (element.AttendeeId == attId) {
  //             element.activeUser = true;
  //           }
  //         });
  //         me.AttendeesCount = me.Attendees.filter((x) => x.activeUser).length;
  //         me.updateTiles(me.meetingSession);
  //       },
  //     };
  //     this.meetingSession.audioVideo.addObserver(observer);
  //     const audioOutputElement = document.getElementById(
  //       'meeting-audio'
  //     ) as HTMLAudioElement;
  //     this.meetingSession.audioVideo.bindAudioElement(audioOutputElement);
  //     this.meetingSession.audioVideo.start();
  //     this.meetingSession.audioVideo.startLocalVideoTile();
  //   } catch (err) {
  //     console.error(err);
  //   }
  // }
  // async openDevicePopup() {
  //   this.chooseDevicePopup = true;
  // }
  // async closeDevicePopup() {
  //   this.chooseDevicePopup = false;
  //   if (this.videoDevices.length > 0) {
  //     await this.meetingSession.audioVideo.chooseVideoInputDevice(
  //       this.videoDevices[0].deviceId
  //     );
  //   }
  //   if (this.audioDevices.length > 0) {
  //     await this.meetingSession.audioVideo.chooseAudioInputDevice(
  //       this.audioDevices[0].deviceId
  //     );
  //   }
  //   this.meetingSession.audioVideo.stopLocalVideoTile();
  //   this.meetingSession.audioVideo.startLocalVideoTile();

  //   this.meetingSession.audioVideo.realtimeSubscribeToReceiveDataMessage(
  //     this.MeetingResponse.meeting.Meeting.MeetingId,
  //     (data) => {
  //       this.getSingleMessage(this.db_meeting_id);
  //     }
  //   );
  // }
  // async chooseDeviceClick() {
  //   this.chooseDevicePopup = false;
  //   let audioDevices_check = await this.meetingSession.audioVideo.listAudioInputDevices();
  //   let videoDevices_check = await this.meetingSession.audioVideo.listVideoInputDevices();

  //   if (videoDevices_check.length > 0) {
  //     if (this.selectedVideo) {
  //       await this.meetingSession.audioVideo.chooseVideoInputDevice(
  //         this.selectedVideo
  //       );
  //     }
  //   }
  //   if (audioDevices_check.length > 0) {
  //     if (this.selectedAudio) {
  //       await this.meetingSession.audioVideo.chooseAudioInputDevice(
  //         this.selectedAudio
  //       );
  //     }
  //   }
  //   this.meetingSession.audioVideo.stopLocalVideoTile();
  //   this.meetingSession.audioVideo.startLocalVideoTile();

  //   setTimeout(() => {
  //     const localTileId = this.meetingSession.audioVideo
  //       .getLocalVideoTile()
  //       .id();
  //     let video = document.getElementById(
  //       'video-' + localTileId
  //     ) as HTMLVideoElement;
  //     video.style.opacity = '0.3';
  //     video.pause();
  //     this.IsStartVideo = false;
  //     this.saveLog('pause');
  //     this.meetingSession.audioVideo.realtimeSendDataMessage(
  //       this.MeetingResponse.meeting.Meeting.MeetingId,
  //       'Pause'
  //     );
  //   }, 1000);
  //   this.meetingSession.audioVideo.realtimeSubscribeToReceiveDataMessage(
  //     this.MeetingResponse.meeting.Meeting.MeetingId,
  //     (data) => {
  //       this.getSingleMessage(this.db_meeting_id);
  //     }
  //   );
  // }
  // async changeAudioVideoSource() {
  //   this.getMediaDevices();
  //   var audioInputs = [];
  //   audioInputs = await this.meetingSession.audioVideo.listAudioInputDevices();
  //   this.audioDevices = [];
  //   if (audioInputs.length > 0) {
  //     for (const input of audioInputs) {
  //       this.audioDevices.push({
  //         deviceId: input.deviceId,
  //         label: input.label,
  //       });
  //     }
  //   }
  //   var videoInputs =
  //     await this.meetingSession.audioVideo.listVideoInputDevices();
  //   this.videoDevices = [];
  //   for (const input of videoInputs) {
  //     this.videoDevices.push({
  //       deviceId: input.deviceId,
  //       label: input.label,
  //     });
  //   }
  //   this.openDevicePopup();
  // }
  // async getMediaDevices() {
  //   try {
  //     await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
  //   } catch (error) {
  //   }
  // }
  // updateTiles(meetingSession) {
  //   const tiles = meetingSession.audioVideo.getAllVideoTiles();
  //   let videoElements = document.querySelectorAll('video');
  //   tiles.forEach((tile) => {
  //     let tileId = tile.id();
  //     let state = tile.state();
  //     if (
  //       state.boundAttendeeId == this.AdminAttendeeId ||
  //       state.boundAttendeeId == this.MyAttendeeId ||
  //       state.isContent
  //     ) {
  //       let videoElement = document.getElementById(
  //         'video-' + tileId
  //       ) as HTMLVideoElement;
  //       if (!videoElement) {
  //         videoElement = document.createElement('video');
  //         videoElement.id = 'video-' + tileId;
  //         if (state.boundAttendeeId == this.MyAttendeeId) {
  //           if (window.innerWidth <= 768) {
  //             videoElement.style.bottom = '155px';
  //           }else{
  //             videoElement.style.bottom = '0';
  //           }
  //           videoElement.style.width = '125px';
  //           videoElement.style.height = '125px';
  //           videoElement.style.position = 'absolute';
  //           videoElement.style.left = '0';           
  //           videoElement.style.borderRadius = '50%';
  //           videoElement.style.border = 'solid 3px #f050ac';
  //         } else {
  //           videoElement.style.width = '100%';
  //           videoElement.style.height = '100%';
  //         }
  //         document.getElementById('video-list').append(videoElement);
  //         meetingSession.audioVideo.bindVideoElement(tileId, videoElement);
  //         this.AttendeesCount = this.Attendees.filter(
  //           (x) => x.activeUser
  //         ).length;
  //       }
  //     }
  //   });
  //   if (videoElements.length >= 3) {
  //     videoElements[1].remove();
  //   }
  // }

  // async startStopVideo() {
  //   const localTileId = this.meetingSession.audioVideo.getLocalVideoTile().id();
  //   if (this.IsStartVideo) {
  //     try {
  //       let video = document.getElementById(
  //         'video-' + localTileId
  //       ) as HTMLVideoElement;
  //       video.style.opacity = '0.3';
  //       video.pause();
  //       this.saveLog('pause');
  //       this.IsStartVideo = false;
  //     } catch (error) {
  //       console.log(`Error stopping video: ${error}`);
  //     }
  //   } else {
  //     try {
  //       let video = document.getElementById(
  //         'video-' + localTileId
  //       ) as HTMLVideoElement;
  //       video.style.opacity = '1';
  //       video.play();
  //       this.saveLog('play');
  //       this.IsStartVideo = true;
  //     } catch (error) {
  //       console.log(`Error starting video: ${error}`);
  //     }
  //   }
  // }

  // muteAudio() {
  //   if (this.IsMuted) {
  //     if (this.muteByPresenter) {
  //       Swal.fire('Sorry', 'Presenter has been muted your audio', 'error');
  //     } else {
  //       this.meetingSession.audioVideo.realtimeUnmuteLocalAudio();
  //       this.IsMuted = !this.IsMuted;
  //     }
  //   } else {
  //     this.meetingSession.audioVideo.realtimeMuteLocalAudio();
  //     this.IsMuted = !this.IsMuted;
  //   }
  // }
  // endMeeting() {
  //   Swal.fire({
  //     title: 'Leave Meeting?',
  //     icon: 'warning',
  //     showCancelButton: true,
  //     confirmButtonColor: '#3085d6',
  //     cancelButtonColor: '#d33',
  //     confirmButtonText: 'Yes',
  //   }).then(async (result) => {
  //     if (result.value) {
  //       await this.saveLog('left');
  //       if (this.meetingSession) {
  //         this.meetingSession.audioVideo.stop();
  //         this.meetingSession.audioVideo.chooseVideoInputDevice(null);
  //         this.meetingSession.audioVideo.stopLocalVideoTile();
  //       }
  //       window.location.href = 'sidenav/dashboard';
  //     }
  //   });
  // }
}
