import { Component, OnInit, ViewChild, HostListener } from '@angular/core';
import { Toast, validator, serializeFormData } from 'assets/js/common.js';
declare var $: any;
import * as AgoraRTC from 'agora-rtc-sdk';
import { LocalStorage } from '../../core/services/local_storage.service';
import { HyperService } from '../../core/services/http.service';
import { Router } from "@angular/router";
import { CONFIG } from "../../config";
import { MySchedulesComponent } from '../myschedule/myschedule.component';
import * as moment from 'moment';
import { ConfirmpopComponent } from '../confirmpop/confirmpop.component';
import { Observable } from 'rxjs/Observable';
import { ToasterService } from '../../core/services/toaster.service';

@Component({
  selector: 'app-myschedule-details',
  templateUrl: './myschedule-details.component.html',
  styleUrls: ['./myschedule-details.component.scss']
})
export class MyschedulesDetailsComponent implements OnInit {
  is_modal_visible_chat: boolean = false;
  screen_callback: any;
  content_data: any;
  channelName: any;
  msgcollection: any = [];
  channelMessage: string;
  msg: any;
  reqjson: any;
  is_modal_list_chat: boolean = false;
  accountname: any;
  participant_list: any;
  isbroad_caster: boolean = false;
  singledselist: any;
  loader: boolean;
  uidvalue: any;
  prev_data: any;
  is_modal_addparticipant: boolean = false;
  rm_list: any=[];
  am_list: any=[];
  showam: boolean;
  showdealer: boolean;
  dealer_list: any=[];
  extended_type = '';
  dse_list: any=[];
  showdse: boolean;
  typermdata: any = [];
  typeamdata: any = [];
  typedealerdata: any = [];
  typedsedata: any = [];
  bullet_in: any;
  index: any;
  is_modal_delete: boolean;
  trainingid: any;
  today: any;
  modifieddata: any;
  showrequestlayout_dse: boolean;
  showreq_acceptlayout_dse: boolean = false;
  requeter_details: void;
  startbroadcaster: boolean = false;
  startpresent_layout: boolean;
  getrequest_details: any;
  stoppresent_layout: boolean;
  ulist: any;
  activeuserslength: any;
  liststatuscount: Array<{ status: string }> = [];
  last: any;
  firstvalue: any;
  secondvalue: any;
  differencevalue: any;
  training_id: any;
  showunmuteaudio: boolean = false;
  showchatval: boolean = false;
  showparticipantval: any = false;
  showmuteaudio: boolean = true;
  showunmutevideo: boolean = false;
  showmutevideo: boolean = true
  timeLeft: number = 15;
  interval;
  mChannelMemberCount = 1;
  msgcollectionlist = [];
  chatdot = false;
  req_text;
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  timerVar: any;
  broadcastercast: string;
  active_product:number;

  totaltime: number = 0;
  fromtime; any;
  totime: any;
  timetakenvalue: number = 0;
  concurrentid: any;
  minutesleft: number = 0;
  secondsdisplay: any;
  minutesdisplay: any;
  now: any;
  year: any;
  month: any;
  day: any;
  hour: any;
  minute: any;
  second: any;
  share_screen: boolean = false;
  timeleft_video: any = 0;
  showtime: boolean;
  totaltimelist: any;
  timeString: string;
  timeStrings_user: string;
  interval_video: any;
  channel_profile: any;
  channel_userName: any;
  user_role: any;
  user_role_am_mail: any=[];
  user_role_dealer_mail: any=[];
  user_role_dse_mail: any=[];
  totalparticipant_list=[];
  is_modal_leave_popup: boolean = false;
  interval_organiser: any;
  timeLeft_organiser: any;
  showmute_presenter_video: boolean = false;
  showmute_presenter_audio: boolean = false;
  showunmute_presenter_video: boolean = false;
  showunmute_presenter_audio: boolean = false;

  typezmuserdata: any=[];
  typermuserdata: any=[];
  typeamuserdata: any=[];
  totalzmparticipant_list : any =[];
  totalrmparticipant_list : any =[];
  totalamparticipant_list : any =[];
  zm_userlist:any =[];
  rm_userlist:any =[];
  am_userlist:any =[];
  showzmuser: boolean = false;
  showrmuser: boolean = false;
  showamuser: boolean = false;
  @HostListener('window:unload', ['$event'])
  unloadHandler(event) {
    this.leavechannel();
    this.sleep(5000);
    event.returnValue = "Are you sure?";
  }

  sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
  }

  @HostListener('window:beforeunload', [ '$event' ])
  beforeUnloadHandler(event) {
    event.returnValue = "Are you sure?";
  }

  @HostListener('window:popstate', ['$event'])
  onPopState(event) {
    this.leavechannel();
    // if (confirm('Are you sure to leave training?')) {
    //   this.leavechannel();
    // } else {
    //   // window.history.go()
    //   this.leavechannel();
    //   // $("#" + dataModal).css({ "display": "flex" });
    //   // $('body').css('position', 'fixed');
    // }
    
  }

  constructor(private server: HyperService, private router: Router,private toaster: ToasterService) {

  }

  ngOnInit() {
  }

  ngOnChanges() {

  }

  getTrainingList() {
    this.loader = true
    this.server.get("videotraining?page=0&limit=10")
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
          this.loader = false;
          this.bullet_in = data.result.data;
          this.datechecking();
          // this.isBroadcaster();
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.loader = false;
          this.router.navigateByUrl('');
        }
      });
  }

  datechecking() {
    var today = new Date();
    for (let i = 0; i < this.bullet_in.length; i++) {
      if (new Date(this.bullet_in[i].todate) > today) {
        this.bullet_in[i].btnstatus = true;
      } else {
        this.bullet_in[i].btnstatus = false;
      }
      this.accountname = LocalStorage.getValue('user_data').emp_code;
      if (this.accountname == this.bullet_in[i].organiser) {
        this.bullet_in[i].broadcaster = true;
      } else {
        this.bullet_in[i].broadcaster = false;
      }
      if (new Date(this.bullet_in[i].fromdate) > today) {
        this.bullet_in[i].cmd = 'Yet to be Start';
      } else if (new Date(this.bullet_in[i].fromdate) < today && new Date(this.bullet_in[i].todate) < today) {
        this.bullet_in[i].cmd = 'Ended';
      } else {
        this.bullet_in[i].cmd = 'Join';
      }
    }
    this.singledselist = this.bullet_in[this.index];
    this.isbroad_caster = this.singledselist.broadcaster;
    this.participant_list = this.singledselist.userlist;
  }

  public showpopupmodal(url: string = "", data: any = {}, position: any, callBack: any = null) {
    this.singledselist = data;
    this.index = position;
    this.isbroad_caster = this.singledselist.broadcaster;
    this.participant_list = this.singledselist.userlist;
    this.calculateclosedtiming();
    this.calculatestatus();
    this.is_modal_list_chat = true;
    this.screen_callback = callBack;
  }

  public showdeletepopupmodal(url: string, data: any, callBack: any = null) {
    this.trainingid = data;
    this.is_modal_delete = true;
    this.screen_callback = callBack;
  }

  calculatestatus(){
    var today = new Date();
    if(this.singledselist.cmd == 'Join'){
      var d1:any = moment(this.singledselist.fromdate,'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm')
      var d2:any = moment(today,'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm')
      d1 = new Date(d1);
      d2 = new Date(d2);
      if(d1.getTime() > d2.getTime()){
        this.singledselist.btn_enable = true;
      }else{
        this.singledselist.btn_enable = false;
      }
    }
  }

  onLogType(type) {
    if (type == 1) {
      this.loader = true;
      this.server.delete("videotraining/" + this.trainingid).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.router.navigateByUrl('myschedules');
          this.screen_callback(true);
          this.is_modal_delete = false;
        } else if (data.result.response == "failed") {

        }
      })
    } else {
      this.is_modal_delete = false;
    }
  }

  CloseaddparticipantModal() {
    this.is_modal_addparticipant = false;
    this.reset();
  }

  CloseModal() {
    this.is_modal_list_chat = false;
    if (this.singledselist.status && this.singledselist.cmd == 'Yet to be Start') {
      this.screen_callback(true)
    }
    this.active_product = null;
  }

  removesmpin(user_id) {
    let trainingid = this.singledselist.id;
    this.is_modal_addparticipant = false;
    this.loader = true;
    this.server.delete("videotraining/scheduleusers/" + trainingid + "/" + user_id).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.getTrainingList();
      } else if (data.result.response == "failed") {

      }
    })
  }

  enableaddsmpin() {
    this.is_modal_addparticipant = true;
    this.user_role = LocalStorage.getValue('user_data').role;
    // this.check_role_login();
    this.getRmlist();
    this.getuserlist();
  }

  check_role_login(){
    if(this.user_role == 5 || this.user_role == 4){
      this.getRmlist();
    }else if(this.user_role == 6){
      this.getAmlist();
    }else if(this.user_role == 7){
      this.getdealerlist();
    }else if(this.user_role == 14){
      this.getdselist();
    }
  }

  getuserlist(){
    this.server.post("common/ilearnuserlist",{ role : 4 })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showzmuser = true;
        this.zm_userlist = data.result.data;
      }else{
        this.showzmuser = false;
      }
    })

    this.server.post("common/ilearnuserlist",{ role : 6 })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.rm_userlist = data.result.data;
        this.showrmuser = true;
      }else{
        this.showrmuser = false;
      }
    })

    this.server.post("common/ilearnuserlist",{ role : 7 })
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.am_userlist = data.result.data;
        this.showamuser = true;
      }else{
        this.showamuser = false;
      }
    })
  }

  getRmlist(){
    this.server.post("common/trainerrm", '')
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed') {
        this.rm_list = data.result.data;
      }
    })
  }

  getAmlist(){
    this.user_role_am_mail.push(LocalStorage.getValue('user_data').emailid);
    let senddata = {};
    senddata = {"rm_email":JSON.stringify(this.user_role_am_mail)}
    this.server.post("common/traineram",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showam = true;
        this.am_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.am_list=[];
        this.showam =false;
        this.showdealer =false;
        this.showdse =false;
      }
  })
  }

  getdealerlist(){
    this.user_role_dealer_mail.push(LocalStorage.getValue('user_data').emailid);
    let senddata = {};
    senddata = {"am_email":JSON.stringify(this.user_role_dealer_mail)}
    this.server.post("common/trainerdealer",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdealer = true;
        this.dealer_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dealer_list=[];
        this.showdealer =false;
        this.showdse =false;
      }
  })
  }

  getdselist(){
    this.user_role_dse_mail.push(LocalStorage.getValue('user_data').dealer_code);
    let senddata = {};
    senddata = {"dealer_code":JSON.stringify(this.user_role_dse_mail)}
    this.server.post("common/dselist",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdse = true;
        this.dse_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dse_list=[];
        this.typedsedata=[];
        this.showdse =false;
      }
  })
  }

  Changezmuser(event,i){
    this.totalzmparticipant_list =[];
    var value=event.target.value;
    const index = this.typezmuserdata.indexOf(value);
    if(event.target.checked){
      this.typezmuserdata.push(event.target.value);
      this.displayzmlist(this.typezmuserdata);
    }else{
      if (index > -1) {
        this.typezmuserdata.splice(index, 1);
        this.displayzmlist(this.typezmuserdata);
      }
    }
  }

  displayzmlist(data){
    this.totalzmparticipant_list=[];
    for(let i=0;i<this.zm_userlist.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.zm_userlist[i].userid==data[j]){
          this.totalzmparticipant_list.push(this.zm_userlist[i]);
        }
      }
    }
  }

  Changermuser(event,i){
    this.totalrmparticipant_list =[];
    var value=event.target.value;
    const index = this.typermuserdata.indexOf(value);
    if(event.target.checked){
      this.typermuserdata.push(event.target.value);
      this.displayrmlist(this.typermuserdata);
    }else{
      if (index > -1) {
        this.typermuserdata.splice(index, 1);
        this.displayrmlist(this.typermuserdata);
      }
    }
  }

  displayrmlist(data){
    this.totalrmparticipant_list=[];
    for(let i=0;i<this.rm_userlist.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.rm_userlist[i].userid==data[j]){
          this.totalrmparticipant_list.push(this.rm_userlist[i]);
        }
      }
    }
  }

  Changeamuser(event,i){
    this.totalamparticipant_list =[];
    var value=event.target.value;
    const index = this.typeamuserdata.indexOf(value);
    if(event.target.checked){
      this.typeamuserdata.push(event.target.value);
      this.displayamlist(this.typeamuserdata);
    }else{
      if (index > -1) {
        this.typeamuserdata.splice(index, 1);
        this.displayamlist(this.typeamuserdata);
      }
    }
  }

  displayamlist(data){
    this.totalamparticipant_list=[];
    for(let i=0;i<this.am_userlist.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.am_userlist[i].userid==data[j]){
          this.totalamparticipant_list.push(this.am_userlist[i]);
        }
      }
    }
  }

  reset() {
    this.rm_list = [];
    this.am_list = [];
    this.dealer_list = [];
    this.dse_list = [];
    this.totalparticipant_list = [];
    this.typezmuserdata = [];
    this.typermuserdata = [];
    this.typeamuserdata = [];
    this.totalzmparticipant_list =[];
    this.totalrmparticipant_list =[];
    this.totalamparticipant_list =[];
    this.zm_userlist =[];
    this.rm_userlist =[];
    this.am_userlist =[];
    this.showzmuser = false;
    this.showrmuser = false;
    this.showamuser = false;
    this.showam = false;
    this.showdealer = false;
    this.showdse = false;
  }

  addsmpin() {
    var a=this.typedsedata.concat(this.typezmuserdata,this.typermuserdata);
    let senddata = {};
    senddata = {
      "trainingid": this.singledselist.id,
      "userid": JSON.stringify(a.concat(this.typeamuserdata))
    }
    this.loader = true;
    this.server.post("videotraining/scheduleusers", senddata).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.is_modal_addparticipant = false;
        this.getTrainingList();
        this.reset();
        // this.screen_callback(true);
      } else if (data.result.response == "failed") {

      }
    })
  }

  Changerm(event, i) {
    this.typedealerdata = [];
    this.typedsedata = [];
    this.totalparticipant_list=[];
    this.showdealer = false;
    this.showdse = false;
    var value = event.target.value;
    var senddata = {};
    const index = this.typermdata.indexOf(value);
    if (event.target.checked) {
      this.typermdata.push(event.target.value);
    } else {
      if (index > -1) {
        this.typermdata.splice(index, 1);
      }
    }
    senddata = { "rm_email": JSON.stringify(this.typermdata) }
    this.server.post("common/traineram", senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          this.showam = true;
          this.am_list = data.result.data;
          // this.participant_data = data.result.data.participant;
        } else {
          this.am_list = [];
          this.showam = false;
          this.showdealer = false;
          this.showdse = false;
        }
      })
  }
  Changeam(event, i) {
    this.typedealerdata = [];
    this.typedsedata = [];
    this.totalparticipant_list=[];
    this.showdse = false;
    var value = event.target.value;
    var senddata = {};
    const index = this.typeamdata.indexOf(value);
    if (event.target.checked) {
      this.typeamdata.push(event.target.value);
    } else {
      if (index > -1) {
        this.showdealer = false;
        this.typeamdata.splice(index, 1);
      }
    }
    senddata = { "am_email": JSON.stringify(this.typeamdata) }
    this.server.post("common/trainerdealer", senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          this.showdealer = true;
          this.dealer_list = data.result.data;
          // this.participant_data = data.result.data.participant;
        } else {
          this.dealer_list = [];
          this.showdealer = false;
          this.showdse = false;
        }
      })
  }
  Changedealer(event, i) {
    this.typedsedata = [];
    this.totalparticipant_list=[];
    var value = event.target.value;
    var senddata = {};
    const index = this.typedealerdata.indexOf(value);
    if (event.target.checked) {
      this.typedealerdata.push(event.target.value);
    } else {
      if (index > -1) {
        this.showdse =false;
        this.typedealerdata.splice(index, 1);
      }
    }
    senddata = { "dealer_code": JSON.stringify(this.typedealerdata) }
    this.server.post("common/dselist", senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {
          this.showdse = true;
          this.dse_list = data.result.data;
          // this.participant_data = data.result.data.participant;
        } else {
          this.dse_list = [];
          this.typedsedata = [];
          this.showdse = false;
        }
      })
  }
  Changedse(event) {
    this.totalparticipant_list =[];
    var value = event.target.value;
    var senddata = {};
    const index = this.typedsedata.indexOf(value);
    if (event.target.checked) {
      this.typedsedata.push(event.target.value);
      this.displaylist(this.typedsedata)
    } else {
      if (index > -1) {
        this.typedsedata.splice(index, 1);
        this.displaylist(this.typedsedata)
      }
    }
  }

  displaylist(data){
    this.totalparticipant_list=[];
    for(let i=0;i<this.dse_list.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.dse_list[i].userid==data[j]){
          this.totalparticipant_list.push(this.dse_list[i]);
        }
      }
    }
  }

  public showcontentrModalchat(url: string = "", data: any = {}, list: any, callBack: any = null) {
    this.today = new Date();
    this.prev_data = list;
    this.showrequestlayout_dse = false;
    this.showreq_acceptlayout_dse = false;
    this.stoppresent_layout = false;
    this.startpresent_layout = false;
    this.channelName = list.channel;
    this.training_id = list.id
    this.is_modal_visible_chat = true;
    this.is_modal_leave_popup = false;  
    this.content_data = data;
    this.screen_callback = callBack;
    this.accountname = LocalStorage.getValue('user_data').emp_code;
    CONFIG.rtm.joinChannel(this.channelName).then(() => {
      this.subscribeRTMListener();
      if (this.isBroadcaster()) {
        this.channel_profile = LocalStorage.getValue('user_data').profile_photo;
        this.channel_userName = LocalStorage.getValue('user_data').fname;
        this.sendProfile1();
      } else {
        this.req_text = 'Request';
        this.showrequestlayout_dse = true;
        this.requestProfile();
        this.checkorganiser_status();
      }
    }).catch((err) => {
    })

    CONFIG.rtcobj;
    this.rtcinitalization();
    this.getchannelmsg();
  }

  subscribeRTMListener() {
    CONFIG.rtm.on('MemberJoined', ({ args }) => {
      this.mChannelMemberCount++;
    })

    CONFIG.rtm.on('MemberLeft', ({args }) => {
      this.mChannelMemberCount--;
    })

    CONFIG.rtm.getMembers().then((members) => {
      this.mChannelMemberCount = members.length;
      })
    .catch((ex) => {
      });
    // this.mChannelMemberCount = members.length;

    CONFIG.rtm.on('ChannelMessage', ({args}) => {
      const [message, memberId] = args;
      this.requeter_details = JSON.parse(message.text);
      this.checkchatconditions(message.text);
    })
  }

  getchannelmsg() {
    this.loader = true
    this.server.get("videotraining/message/" + this.prev_data.id)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
          this.loader = false;
          this.msgcollectionlist = data.result.data;
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.loader = false;
          this.router.navigateByUrl('');
        }
      });
  }

  public checkorganiser_status(){
    this.interval_organiser = setInterval(() => {
      this.leavechannel();
    }, 1000*300)
  }

  public sendorganiserstatus(status){
    this.reqjson = {
      "canPresent": status,
      "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
      "id": 'All',
      "isRequesPresent": false,
      "isRequesProfile": false,
      "isRequest": false,
      "isResponse": true,
      "isResponsePresent": true,
      "isResponseProfile": false,
      "message": "",
      "name": LocalStorage.getValue('user_data').fname,
      "profile": LocalStorage.getValue('user_data').profile_photo
    }
    CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
    }).catch((err) => {
    })
  }

  public sendProfile1() {
    this.reqjson = {
      "canPresent": 1,
      "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
      "id": 'All',
      "isRequesPresent": false,
      "isRequesProfile": false,
      "isRequest": false,
      "isResponse": true,
      "isResponsePresent": false,
      "isResponseProfile": true,
      "message": "",
      "name": LocalStorage.getValue('user_data').fname,
      "profile": LocalStorage.getValue('user_data').profile_photo
    }
    // this.channelmsg(JSON.stringify(this.reqjson));
    CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
    }).catch((err) => {
    })
    this.sendorganiserstatus(4);
  }

  requestProfile() {
    this.reqjson = {
      "canPresent": 1,
      "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
      "id": this.isBroadcaster() ? LocalStorage.getValue('user_data').emp_code : LocalStorage.getValue('user_data').smpin,
      "isRequesPresent": false,
      "isRequesProfile": true,
      "isRequest": true,
      "isResponse": false,
      "isResponsePresent": false,
      "isResponseProfile": false,
      "message": "",
      "name": LocalStorage.getValue('user_data').fname,
      "profile": LocalStorage.getValue('user_data').profile_photo
    }
    // this.channelmsg(JSON.stringify(this.reqjson));
    CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
    }).catch((err) => {
    })
  }

  send_channel_message() {
    const params = serializeFormData('loginForm')
    this.reqjson = {
      "canPresent": 1,
      "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
      "id": this.isBroadcaster() ? LocalStorage.getValue('user_data').emp_code : LocalStorage.getValue('user_data').smpin,
      "isRequesPresent": false,
      "isRequesProfile": false,
      "isRequest": false,
      "isResponse": false,
      "isResponsePresent": false,
      "isResponseProfile": false,
      "message": params.channelMessage,
      "name": LocalStorage.getValue('user_data').fname,
      "profile": LocalStorage.getValue('user_data').profile_photo
    }
    if(this.isBroadcaster()){
      CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
        if (params.channelMessage != null && params.channelMessage != undefined) {
          this.msgcollectionlist.push(this.reqjson)
          this.postchannelmsg(params.channelMessage);
        }
        $("#end").animate({ scrollTop: $('#end').prop("scrollHeight")}, 1000);
      }).catch((err) => {
        Toast.error('Send message to channel ' + params.channelName + ' failed, please open console see more details.')
      })
      this.channelMessage = '';
      this.msg = params.channelMessage;
    }else{
      if ($("#client_view_display>div.video-view.fullrow").length > 0 || $("#client_view_display>div.video-view.w50").length > 0) {
        CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
          if (params.channelMessage != null && params.channelMessage != undefined) {
            this.msgcollectionlist.push(this.reqjson)
            this.postchannelmsg(params.channelMessage);
          }
          $("#end").animate({ scrollTop: $('#end').prop("scrollHeight")}, 1000);
        }).catch((err) => {
          Toast.error('Send message to channel ' + params.channelName + ' failed, please open console see more details.')
        })
        this.channelMessage = '';
        this.msg = params.channelMessage;
      }
      else{
        this.toaster.show('Organisor not joined, try again!')
      }
    }
  }

  postchannelmsg(msg) {
    let senddata = { "msg": msg, "sid": this.prev_data.id }
    this.server.post("videotraining/message", senddata)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed') {

        } else {
        }
      })
  }

  checkchatconditions(chat) {
    let msg = JSON.parse(chat)
    if (msg.isRequest) {
      if (this.isBroadcaster()) {
        if (msg.isRequesProfile) {
          this.sendProfile(msg);
        } else if (msg.isRequesPresent) {
          if (CONFIG.rtcobj.isPresentSomeOne || CONFIG.rtcobj.isScreenshare) {
            this.sendSomeonePresent(msg);
          } else {
            CONFIG.rtcobj.isPresentSomeOne = true;
            // REQUESTED_CHAT = chat;
            this.enabelPermissionLayout(msg);
          }
        }
      }
    } else if (msg.isResponse) {
      if (!this.isBroadcaster()) {
        if (msg.isResponseProfile) {
          this.setProfile(msg);
        } else if (msg.isResponsePresent) {
          if (msg.canPresent == 0) { //Accept
            this.startPresent(msg);
          } else if (msg.canPresent == 1) { //Decline
            this.declinePresent(msg);
            this.req_text = "Request";
          } else if (msg.canPresent == 2) { //Dismiss
            this.dismissPresent(msg);
            this.req_text = "Request";
          } else if (msg.canPresent == 3) { //Someone Present
            let id = LocalStorage.getValue('user_data').smpin;
            if (msg.id == id) {
              this.req_text = "Request";
              this.toaster.show('Someone was presenting, try again!');
            }
          }else if (msg.canPresent == 4) { // OrganiserJoined
           clearInterval(this.interval_organiser);
          }else if (msg.canPresent == 5) { //OrganiserDismissed
            // this.timeLeft_organiser = 180;
            this.interval_organiser = setInterval(() => {
              this.leavechannel();
            }, 1000*180)
          }
        }
      } else {
        this.startpresent_layout = false;
        CONFIG.rtcobj.isPresentSomeOne = false;
        this.stoppresent_layout = false;
      }
    } else {
      // this.channelmsg(chat);
      // this.msgcollectionlist.push({
      //   "message" : JSON.parse(chat),
      // })
      if(!this.showchatval){
        this.chatdot = true;
      }
      this.msgcollectionlist.push(JSON.parse(chat));
      $("#end").animate({ scrollTop: $('#end').prop("scrollHeight")}, 1000);
    }
  }

  public sendProfile(chat) {
    this.reqjson = {
      "canPresent": 1,
      "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
      "id": chat.id,
      "isRequesPresent": false,
      "isRequesProfile": false,
      "isRequest": false,
      "isResponse": true,
      "isResponsePresent": false,
      "isResponseProfile": true,
      "message": "",
      "name": chat.name,
      "profile": chat.profile
    }
    // this.channelmsg(JSON.stringify(this.reqjson));
    CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
    }).catch((err) => {
      console.error(err)
    })
  }

  sendSomeonePresent(msg) {
    this.reqjson = {
      "canPresent": 3,
      "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
      "id": msg.id,
      "isRequesPresent": false,
      "isRequesProfile": false,
      "isRequest": false,
      "isResponse": true,
      "isResponsePresent": true,
      "isResponseProfile": false,
      "message": "",
      "name": msg.name,
      "profile": ''
    }
    // this.channelmsg(JSON.stringify(this.reqjson));
    CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
    }).catch((err) => {
    })
  }

  enabelPermissionLayout(msg) {
    $("#req_display_layout_id").removeClass("nodisplay");
    this.startpresent_layout = false;
    this.getrequest_details = msg;
    this.timeLeft = 15;
    this.showreq_acceptlayout_dse = true;
    // this.timerVar = Observable.interval(1000).subscribe(x => {
    //   this.startTimer();
    // });
    this.startTimer(this.timeLeft);
    // this.showrequestlayout_dse = false;
  }

  isBroadcaster() {
    this.accountname = LocalStorage.getValue('user_data').emp_code;
    if (this.accountname == this.prev_data.organiser) {
      return true;
    } else {
      return false;
    }
  }

  startTimer(time) {
    this.timeLeft = time;
    this.interval = setInterval(() => {
      if (this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.onreqType(2);
      }
    }, 1000)
  }

  onreqType(type) {
    if (type == 0) {
      if ($("#client_view_display>div.video-view.fullrow").length > 0 || $("#client_view_display>div.video-view.w50").length > 0) {
      this.reqjson = {
        "canPresent": 1,
        "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
        "id": this.isBroadcaster() ? LocalStorage.getValue('user_data').emp_code : LocalStorage.getValue('user_data').smpin,
        "isRequest": true,
        "isRequesPresent": true,
        "isRequesProfile": false,
        "isResponse": false,
        "isResponsePresent": false,
        "isResponseProfile": false,
        "message": "",
        "name": LocalStorage.getValue('user_data').fname,
        "profile": ''
      }
      CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
      }).catch((err) => {
        console.error(err)
      })
      this.req_text = "Requested";
      }else{
        this.toaster.show('Organisor not joined, try again!')
        // alert("Organisor not joined, try again!");
      }
    } else if (type == 1) {
      clearInterval(this.interval);
      this.showreq_acceptlayout_dse = false
      this.reqjson = {
        "canPresent": 0,
        "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
        "id": this.getrequest_details.id,
        "isRequesPresent": false,
        "isRequesProfile": false,
        "isRequest": false,
        "isResponse": true,
        "isResponsePresent": true,
        "isResponseProfile": false,
        "message": "",
        "name": this.getrequest_details.name,
        "profile": ''
      }
      CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
      }).catch((err) => {
        console.error(err)
      })
      this.startpresent_layout = true;
    } else if (type == 2) {
      clearInterval(this.interval);
      this.showreq_acceptlayout_dse = false;
      let count = 0;
      if (CONFIG.rtcobj.isPresentSomeOne && this.startpresent_layout) {
        this.reqjson = {
          "canPresent": 2,
          "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
          "id": this.getrequest_details.id,
          "isRequesPresent": false,
          "isRequesProfile": false,
          "isRequest": false,
          "isResponse": true,
          "isResponsePresent": true,
          "isResponseProfile": false,
          "message": "",
          "name": this.getrequest_details.name,
          "profile": ''
        }
        CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
        }).catch((err) => {
          console.error(err)
        })
        this.startpresent_layout = false;
        this.stoppresent_layout = false;
        this.startbroadcaster = false;
        CONFIG.rtcobj.isPresentSomeOne = false;
      } else {
        CONFIG.rtcobj.isPresentSomeOne = false;
        this.startbroadcaster = false;
        this.reqjson = {
          "canPresent": 1,
          "date": moment(this.today, 'YYYY-MM-DD').format("YYYY-MM-DD"),
          "id": this.getrequest_details.id,
          "isRequesPresent": false,
          "isRequesProfile": false,
          "isRequest": false,
          "isResponse": true,
          "isResponsePresent": true,
          "isResponseProfile": false,
          "message": "",
          "name": this.getrequest_details.name,
          "profile": ''
        }

        CONFIG.rtm.sendChannelMessage(JSON.stringify(this.reqjson)).then(() => {
        }).catch((err) => {
          console.error(err)
        })
        this.startpresent_layout = false;
        this.stoppresent_layout = false;
      }
      // this.startbroadcaster = false;

    } else {
      if (CONFIG.rtcobj.localStream != null) {
        CONFIG.rtcobj.localStream.stop();
        CONFIG.rtcobj.localStream.close();

        $("#client_view_display").removeClass("w100");
        $("#host_view_display").removeClass("w100");

        $("#client_view_display").removeClass("wid0");
        $("#host_view_display").removeClass("wid0");

        $("#client_view_display").removeClass("wid50");
        $("#host_view_display").removeClass("wid50");
        $("#req_display_layout_id").removeClass("nodisplay");
        

        $("#client_view_display").addClass("w100");
        this.req_text = "Request";
        CONFIG.rtcobj.client.unpublish(CONFIG.rtcobj.localStream, function (err) {
          console.error(err);
        })
        CONFIG.rtcobj.localStream = null;
      }
      this.stoppresent_layout = false;
      this.showrequestlayout_dse = true;
      this.startpresent_layout = false;
      this.showmute_presenter_audio = false;
      this.showmute_presenter_video = false;
      this.showunmute_presenter_audio = false;
      this.showunmute_presenter_video = false;
    }
  }

  setProfile(msg) {
    if (msg.id == 'All') {
      this.channel_userName = msg.name;
      this.channel_profile = msg.profile;
    } else {
      let id = LocalStorage.getValue('user_data').smpin;
      if (msg.id == id) {
        this.channel_userName = msg.name;
        this.channel_profile = msg.profile;
      }
    }
  }

  startPresent(msg) {
    let id = LocalStorage.getValue('user_data').smpin;
    if (msg.id == id) {
      // CONFIG.rtcobj.client.setClientRole('host');
      CONFIG.rtcobj.localStream = AgoraRTC.createStream({
        streamID: 0,
        audio: true,
        video: true,
        screen: false,
      })
      CONFIG.rtcobj.localStream.init(function () {
        CONFIG.rtcobj.localStream.setVideoProfile("480p_1");
        CONFIG.rtcobj.localStream.play("local_stream");

        $("#client_view_display").removeClass("w100");
        $("#host_view_display").removeClass("w100");

        $("#client_view_display").removeClass("wid0");
        $("#host_view_display").removeClass("wid0");

        $("#client_view_display").removeClass("wid50");
        $("#host_view_display").removeClass("wid50");
        $("#req_display_layout_id").removeClass("nodisplay");

        if ($('#client_view_display').length == 1) {
          $("#client_view_display").addClass("wid50");
          $("#host_view_display").addClass("wid50");
        } else {
          $("#client_view_display").addClass("wid0");
          $("#host_view_display").addClass("w100");
        }

        CONFIG.rtcobj.client.publish(CONFIG.rtcobj.localStream, function (err) {
          console.error(err);
        })
      }, function (err) {
        console.error("init local stream failed ", err);
      });
      this.startbroadcaster = true;
      this.showrequestlayout_dse = false;
      this.stoppresent_layout = true;
      this.showmute_presenter_audio = true;
      this.showmute_presenter_video = true;
      this.showunmute_presenter_audio = false;
      this.showunmute_presenter_video = false;
    }
  }

  declinePresent(msg) {
    let id = LocalStorage.getValue('user_data').smpin;
    if (msg.id == id) {
      this.startbroadcaster = false;
      this.showrequestlayout_dse = true;
      this.toaster.show('Organiser is not accepted your request');
    }
  }

  dismissPresent(msg) {
    let id = LocalStorage.getValue('user_data').smpin;
    if (msg.id == id) {
      this.toaster.show('Organiser dismissed your presentation');
      if (CONFIG.rtcobj.localStream != null) {
        CONFIG.rtcobj.localStream.stop();
        CONFIG.rtcobj.localStream.close();

        $("#client_view_display").removeClass("w100");
        $("#host_view_display").removeClass("w100");

        $("#client_view_display").removeClass("wid0");
        $("#host_view_display").removeClass("wid0");

        $("#client_view_display").removeClass("wid50");
        $("#host_view_display").removeClass("wid50");
        $("#req_display_layout_id").removeClass("nodisplay");

        $("#client_view_display").addClass("w100");
        $("#host_view_display").addClass("wid0");

        CONFIG.rtcobj.client.unpublish(CONFIG.rtcobj.localStream, function (err) {
          console.error(err);
        })
        CONFIG.rtcobj.localStream = null;
      }
      this.startbroadcaster = false;
      this.showrequestlayout_dse = true;
      this.startpresent_layout = false;
      this.stoppresent_layout = false;
      CONFIG.rtcobj.isPresentSomeOne = false;
      this.showmute_presenter_audio = false;
      this.showmute_presenter_video = false;
      this.showunmute_presenter_audio = false;
      this.showunmute_presenter_video = false;
    }
  }

  clickrequest() {
    this.showreq_acceptlayout_dse = true;
    this.showrequestlayout_dse = false;
  }

  onCloseModal(type) {
    this.showchatval = false;
    this.showparticipantval = false;
  }

  //started rtc
  rtcinitalization() {
    if (this.isBroadcaster()) {
      this.broadcastercast = 'host';
    } else {
      this.broadcastercast = 'audience';
    }
    CONFIG.rtcobj.client = AgoraRTC.createClient({ mode: "live", codec: "h264" });
    this.uidvalue = '';

    CONFIG.rtcobj.client.init('1fabd779cd5a4a2abbfc13aec37c5a35', function () {
    }, (err) => {
      console.error(err);
    });
    if (this.prev_data.broadcaster) {
      this.joinmeetingclient('host');
    } else {
      this.joinmeetingclient('audience')
    }
  }

  startTimer_video() {
    this.interval_video = setInterval(() => {
      if (this.timeleft_video < 10) {
        this.secondsdisplay = '0' + this.timeleft_video;
      } else {
        this.secondsdisplay = this.timeleft_video
      }
      if (this.minutesleft == 0) {
        this.minutesdisplay = '00';
      } else if (this.minutesleft < 10) {
        this.minutesdisplay = '0' + this.minutesleft;
      } else {
        this.minutesdisplay = this.minutesleft;;
      }
      if (this.timeleft_video == 60) {
        this.minutesleft = this.minutesleft + 1;
        this.timeleft_video = 0;
        this.timetakenvalue = this.totaltime;
        this.totime = this.getdateandtime();
        this.timerupdationtraining();
      }
      this.totaltime++;
      this.timeleft_video++;
    }, 1000)
  }

  timerupdationtraining() {
    let senddata = {};
    senddata = {
      "sid": this.training_id,
      "timetaken": this.timetakenvalue,
      "fromtime": this.fromtime,
      "totime": this.totime,
      "id": this.concurrentid
    }
    this.server.post("videotraining/updatetime", senddata).then((data) => {
      this.loader = false;
      if (data.result.status == 200 && data.result.response == "success") {
        this.concurrentid = data.result.data;
      } else if (data.result.status == 200 && data.result.response == "failed") {
        this.leavechannel();
      }
    })
  }

  StopTimer_video() {
    clearInterval(this.interval_video);
    this.secondsdisplay = '';
    this.minutesdisplay = '';
    this.minutesleft = 0;
    this.timeLeft = 0;
    this.timeleft_video = 0;
  }

  joinmeetingclient(joinmeetingclient) {
    this.fromtime = this.getdateandtime();
    this.totime = this.getdateandtime();
    this.showunmuteaudio=false;
    this.showmuteaudio = true;
    this.showunmutevideo=false;
    this.showmutevideo = true;
    this.timetakenvalue = 10;
    this.concurrentid = '';
    this.timerupdationtraining();
    this.startTimer_video();
    var option = {
      appID: '1fabd779cd5a4a2abbfc13aec37c5a35',
      channel: this.channelName,
      uid: 0,
      token: null
    }
    CONFIG.rtcobj.client.setClientRole(joinmeetingclient);

    CONFIG.rtcobj.client.join(option.token ? option.token : null, option.channel ? option.channel : null, option.uid ? option.uid : null, function (uid) {
      CONFIG.rtcobj.role = joinmeetingclient;
      if (joinmeetingclient == 'host') {
        CONFIG.rtcobj.localStream = AgoraRTC.createStream({
          streamID: 0,
          audio: true,
          video: true,
          screen: false,
        })
    
        CONFIG.rtcobj.localStream.init(function () {
          CONFIG.rtcobj.localStream.setVideoProfile("480p_1");
          CONFIG.rtcobj.localStream.play("local_stream");
          CONFIG.rtcobj.client.publish(CONFIG.rtcobj.localStream, function (err) {
            console.error(err);
          })

        }, function (err) {
        });
      }
    }, function (err) {
      console.error("Channel Join Failure", err)
    })

    CONFIG.rtcobj.client.on("stream-added", function (evt) {
      var remoteStream = evt.stream;
      var id = remoteStream.getId();

      if (id != 0) {
        CONFIG.rtcobj.client.subscribe(remoteStream, function (err) {
        })
      }
    });

    CONFIG.rtcobj.client.on("stream-subscribed", function (evt) {
      var remoteStream = evt.stream;
      var id = remoteStream.getId();
      $("#client_view_display").removeClass("w100");
      $("#host_view_display").removeClass("w100");

      $("#client_view_display").removeClass("wid0");
      $("#host_view_display").removeClass("wid0");

      $("#client_view_display").removeClass("wid50");
      $("#host_view_display").removeClass("wid50");
      $("#req_display_layout_id").removeClass("nodisplay");

      $("<div/>", {
        id: "remote_video_panel_" + id,
        class: "video-view fullrow",
      }).appendTo("#client_view_display");
      $("<div/>", {
        id: "remote_video_" + id,
        class: "video-placeholder fullrow",
      }).appendTo("#remote_video_panel_" + id);
           
      if (CONFIG.rtcobj.role == 'host') {
        $("#client_view_display").addClass("wid50");
        $("#host_view_display").addClass("wid50");
      } else {
        if ($("#client_view_display>div.video-view.fullrow").length > 1) {
          $("#client_view_display").addClass("w100");
          $("#host_view_display").addClass("wid0");
          $("#client_view_display>div.video-view.fullrow").removeClass("fullrow");
          $("#client_view_display>div.video-view").addClass("w50");
        } 
        else {
          $("#client_view_display").addClass("w100");
          $("#host_view_display").addClass("wid0");
          // $("#client_view_display>div.video-view").removeClass("w50");
        }
      }

      remoteStream.play("remote_video_" + id);
    })

    CONFIG.rtcobj.client.on("stream-removed", function (evt) {
      var remoteStream = evt.stream;
      var id = remoteStream.getId();
      // Stop playing the remote stream.
      remoteStream.stop("remote_video_" + id);
      // Remove the view of the remote stream. 
      //this.removeView(id);
      $("#remote_video_panel_" + id).remove();

      $("#client_view_display").removeClass("w100");
      $("#host_view_display").removeClass("w100");

      $("#client_view_display").removeClass("wid0");
      $("#host_view_display").removeClass("wid0");

      $("#client_view_display").removeClass("wid50");
      $("#host_view_display").removeClass("wid50");

      $("#client_view_display").addClass("wid0");
      $("#host_view_display").addClass("w100");
      $("#req_display_layout_id").removeClass("nodisplay");
      $("#client_view_display>div.video-view.w50").removeClass("w50");

      if (CONFIG.rtcobj.role == 'host') {
        $("#client_view_display>div.video-view").addClass("wid0");
        $("#req_display_layout_id").addClass("nodisplay");
        CONFIG.rtcobj.isPresentSomeOne = false;
        CONFIG.rtcobj.localStream.play("local_stream");
        $("#host_view_display").addClass("w100");
      }else {
        $("#client_view_display").addClass("w100");
        $("#client_view_display>div.video-view").addClass("fullrow");
      }
    })

  }

  getuserdetails() {
    this.server.get("videotraining/trainingdse/" + this.training_id)
      .then((data) => {
        if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
          this.ulist = data.result.data;
          this.checkforactiveusers();
          this.activeuserslength = this.liststatuscount.length;
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }

  checkforactiveusers() {
    var dateval = new Date();
    let currenttimesval = dateval.getTime(); 
    let currenttimesvalroundoff = currenttimesval.toFixed(0);

    for (let i = 0; i < this.ulist.length; i++) {
      this.ulist[i].timerlist.length;
      if (this.ulist[i].timerlist.length > 0) {
        this.last = this.ulist[i].timerlist[this.ulist[i].timerlist.length - 1];
        let lastactivetime = this.last.totime;
        var lastactivetimedatevalue = new Date(lastactivetime);
        var lastactivetimeafterconversion = lastactivetimedatevalue.getTime();
        let lastactivetimeafterroundoff = lastactivetimeafterconversion.toFixed(0);
        if (currenttimesvalroundoff > lastactivetimeafterroundoff) {
          this.firstvalue = currenttimesvalroundoff;
          this.secondvalue = lastactivetimeafterroundoff;
        } else {
          this.firstvalue = lastactivetimeafterroundoff;
          this.secondvalue = currenttimesvalroundoff;
        }
        this.differencevalue = this.firstvalue - this.secondvalue;
        if (this.differencevalue < 60000) {
          this.ulist[i].displaystatus = 'active';
          this.liststatuscount.push({ status: 'active' });
        } else {
          this.ulist[i].displaystatus = 'inactive';
          this.liststatuscount.push({ status: 'inactive' });
        }

      } else {
        this.ulist[i].displaystatus = 'inactive';
        this.liststatuscount.push({ status: 'inactive' });
      }
    }
  }

  mute_presenter_audio() {
    CONFIG.rtcobj.localStream.muteAudio();
    this.showunmute_presenter_audio = true;
    this.showmute_presenter_audio = false;
  }

  unmute_presenter_audio() {
    CONFIG.rtcobj.localStream.unmuteAudio();
    this.showunmute_presenter_audio = false;
    this.showmute_presenter_audio = true;
  }

  mute_presenter_video() {
    CONFIG.rtcobj.localStream.muteVideo();;
    this.showunmute_presenter_video = true;
    this.showmute_presenter_video = false;
  }

  unmute_presenter_video() {
    CONFIG.rtcobj.localStream.unmuteVideo();
    this.showunmute_presenter_video = false;
    this.showmute_presenter_video = true;
  }

  muteaudio() {
    this.showunmuteaudio = true;
    this.showmuteaudio = false;
    if(CONFIG.rtcobj.localStream != null){
      CONFIG.rtcobj.localStream.muteAudio();
    }else{
      CONFIG.rtcobj.screenStream.muteAudio();
    }
  }

  unmuteaudio() {
    this.showunmuteaudio = false;
    this.showmuteaudio = true;
    if(CONFIG.rtcobj.localStream != null){
      CONFIG.rtcobj.localStream.unmuteAudio();
    }else{
      CONFIG.rtcobj.screenStream.unmuteAudio();
    }
  }

  mutevideo() {
    CONFIG.rtcobj.localStream.muteVideo();;
    this.showunmutevideo = true;
    this.showmutevideo = false;
  }

  unmutevideo() {
    CONFIG.rtcobj.localStream.unmuteVideo();
    this.showunmutevideo = false;
    this.showmutevideo = true;
  }

  showparticipant($event) {
    this.showparticipantval = !this.showparticipantval;
    this.getuserdetails();
    if(this.showchatval){
      this.showchatval = !this.showchatval;
    }
  }
  showchat($event) {
    this.showchatval = !this.showchatval;
    if (this.showchatval) {
      setTimeout(()=>{ 
          $("#end").animate({ scrollTop:$('#end').prop("scrollHeight")}, 1000);
      }, 200)
    }
    if(this.showparticipantval){
      this.showparticipantval = !this.showparticipantval;
    }
    if(this.chatdot){
      this.chatdot = false;
    }
  }

  sharescreen() {
    this.share_screen = !this.share_screen;
    this.showmuteaudio = true;
    this.showunmuteaudio = false;
    CONFIG.rtcobj.isScreenshare = !CONFIG.rtcobj.isScreenshare;
    if (CONFIG.rtcobj.screenStream != null) {
      CONFIG.rtcobj.screenStream.close();
      CONFIG.rtm.sendChannelMessage(JSON.stringify(CONFIG.share_disable));
      CONFIG.rtcobj.client.unpublish(CONFIG.rtcobj.screenStream, function (err) {
      })
      CONFIG.rtcobj.screenStream = null;

      CONFIG.rtcobj.localStream = AgoraRTC.createStream({
        streamID: 0,
        audio: true,
        video: true,
        screen: false,
      })

      CONFIG.rtcobj.localStream.init(function () {
        CONFIG.rtcobj.localStream.setVideoProfile("480p_1");
        CONFIG.rtcobj.localStream.play("local_stream");
        CONFIG.rtcobj.client.publish(CONFIG.rtcobj.localStream, function (err) {
          console.error(err);
        })

      }, function (err) {
        console.error("init local stream failed ", err);
      });
      return;
    }
    
    if(CONFIG.rtcobj.isPresentSomeOne){
      this.onreqType(2);
    }

    if (CONFIG.rtcobj.localStream != null) {
      CONFIG.rtcobj.localStream.stop();
      CONFIG.rtcobj.localStream.close();

      CONFIG.rtcobj.client.unpublish(CONFIG.rtcobj.localStream, function (err) {
        console.error(err);
      })
      CONFIG.rtcobj.localStream = null;
    }

    const streamSpec = {
      streamID: 0,
      audio: true,
      video: false,
      screen: true,
      screenAudio: false
    }

    CONFIG.rtcobj.screenStream = AgoraRTC.createStream(streamSpec);
    // Initialize the stream.
    CONFIG.rtcobj.screenStream.init(function () {
      console.log("Initialize the stream.for screen share")
      CONFIG.rtm.sendChannelMessage(JSON.stringify(CONFIG.share_enable));
      CONFIG.rtcobj.client.publish(CONFIG.rtcobj.screenStream, function (err) {
        console.error(err);
      })
    }, function (err) {
      CONFIG.rtm.sendChannelMessage(JSON.stringify(CONFIG.share_disable));
      CONFIG.rtcobj.screenStream.close()
      CONFIG.rtcobj.screenStream = null;

      if (CONFIG.rtcobj.localStream == null) {
        CONFIG.rtcobj.localStream = AgoraRTC.createStream({
          streamID: 0,
          audio: true,
          video: true,
          screen: false,
        })
  
        CONFIG.rtcobj.localStream.init(function () {
          CONFIG.rtcobj.localStream.setVideoProfile("480p_1");
          CONFIG.rtcobj.localStream.play("local_stream");
          CONFIG.rtcobj.client.publish(CONFIG.rtcobj.localStream, function (err) {
            console.error(err);
          })
  
        }, function (err) {
          console.error("init local stream failed ", err);
        });
      }
    });
    //===Close the stream===
    CONFIG.rtcobj.screenStream.on("stopScreenSharing", () => {
      CONFIG.rtm.sendChannelMessage(JSON.stringify(CONFIG.share_disable));
      CONFIG.rtcobj.isScreenshare = false;
      CONFIG.rtcobj.screenStream.close();
      CONFIG.rtcobj.client.unpublish(CONFIG.rtcobj.screenStream, function (err) {
        console.error(err);
      })
      CONFIG.rtcobj.screenStream = null;
      
      CONFIG.rtcobj.localStream = AgoraRTC.createStream({
        streamID: 0,
        audio: true,
        video: true,
        screen: false,
      })

      CONFIG.rtcobj.localStream.init(function () {
        CONFIG.rtcobj.localStream.setVideoProfile("480p_1");
        CONFIG.rtcobj.localStream.play("local_stream");
        CONFIG.rtcobj.client.publish(CONFIG.rtcobj.localStream, function (err) {
          console.error(err);
        })

      }, function (err) {
        console.error("init local stream failed ", err);
      });
    });
  }

  leavechannel_popup(){
    this.is_modal_leave_popup = true;
  }

  oncancel(){
    this.is_modal_leave_popup = false;
  }

  leavechannel() {
    if(this.isBroadcaster()){
      this.sendorganiserstatus(5);
    }
    this.is_modal_leave_popup = false;     
    if(this.isBroadcaster() &&  CONFIG.rtcobj.isPresentSomeOne){
      this.onreqType(2);
    }

    if (CONFIG.rtcobj.localStream != null && CONFIG.rtcobj.localStream.isPlaying()) {
      CONFIG.rtcobj.localStream.stop();
      CONFIG.rtcobj.localStream.close();
      CONFIG.rtcobj.client.unpublish(CONFIG.rtcobj.localStream, function (err) {
      })
      setTimeout(()=>{ 
        this.leaveRTCChannel();
       }, 2000)
    }else if (CONFIG.rtcobj.screenStream != null) {
      CONFIG.rtm.sendChannelMessage(JSON.stringify(CONFIG.share_disable));
      CONFIG.rtcobj.screenStream.stop();
      CONFIG.rtcobj.screenStream.close();
      CONFIG.rtcobj.client.unpublish(CONFIG.rtcobj.screenStream, function (err) {
        console.log(err);
      })
      setTimeout(()=>{ 
        this.leaveRTCChannel();
       }, 2000)
    }else {
      this.leaveRTCChannel();
    }    
  }

  leaveRTCChannel() {
    CONFIG.rtcobj.client.leave(function () {
      while (CONFIG.rtcobj.remoteStreams.length > 0) {
        var stream = CONFIG.rtcobj.remoteStreams.shift();
        var id = stream.getId();
        stream.stop();
        $("#remote_video_panel_" + id).remove();
      }
    }, function (err) {
      console.error(err);
    })
    this.leaveRTMChannel();
  }

  leaveRTMChannel() {
    CONFIG.rtm.leaveChannel().then(() => {
      CONFIG.rtm.logout().then(() => {
        CONFIG.rtm._logined = false;
        this.leavePage()
      }).catch((err) => {
        console.error(err)
        this.leavePage()
      })
      
    }).catch((err) => {
      console.error(err)
      this.leavePage()
    })
  }

  leavePage() {
    clearInterval(this.interval_video)
    this.is_modal_visible_chat = false;
    this.screen_callback(true);
    this.StopTimer_video();
    this.showrequestlayout_dse = false;
    this.showreq_acceptlayout_dse = false;
    this.stoppresent_layout = false;
    this.startpresent_layout = false;
    this.share_screen = false;
    CONFIG.rtcobj.isScreenshare = false;
    this.is_modal_leave_popup = false;  
    this.showchatval = false;
    this.showparticipantval = false;
    clearInterval(this.interval_organiser);
    this.showmute_presenter_video = false;
    this.showmute_presenter_audio = false;
    this.showunmute_presenter_video = false;
    this.showunmute_presenter_audio = false;
  }

  leaveRTMChannel1() {
    CONFIG.rtm.leaveChannel().then(() => {
      CONFIG.rtm.logout().then(() => {
        CONFIG.rtm._logined = false;
      }).catch((err) => {
        Toast.error('Leave channel failed, please open console see more details.')
        console.error(err)
      })
      
    }).catch((err) => {
      Toast.error('Leave channel failed, please open console see more details.')
      console.error(err)
    })
    this.is_modal_visible_chat = false;
    this.screen_callback(true);
    this.StopTimer_video();
  }

  getdateandtime() {
    this.now = new Date();
    this.year = "" + this.now.getFullYear();
    this.month = "" + (this.now.getMonth() + 1); if (this.month.length == 1) { this.month = "0" + this.month; }
    this.day = "" + this.now.getDate(); if (this.day.length == 1) { this.day = "0" + this.day; }
    this.hour = "" + this.now.getHours(); if (this.hour.length == 1) { this.hour = "0" + this.hour; }
    this.minute = "" + this.now.getMinutes(); if (this.minute.length == 1) { this.minute = "0" + this.minute; }
    this.second = "" + this.now.getSeconds(); if (this.second.length == 1) { this.second = "0" + this.second; }
    return this.year + "-" + this.month + "-" + this.day + " " + this.hour + ":" + this.minute + ":" + this.second;
  }

  showtiming(index,time){
    if (this.active_product == index) {
      this.active_product = null;
    } else {
        this.active_product = index;
        this.totaltimelist = time.timerlist; 
        this.gettimingsec();
    }
  }
  gettimingsec(){
    var startdate;
    var enddate;
    var hours;
    var minutes;
    for(let i=0; i<this.totaltimelist.length; i++){
      startdate = new Date(this.totaltimelist[i].fromtime);
      enddate = new Date(this.totaltimelist[i].totime);
      var finalmillis = enddate - startdate;
      let seconds = Math.floor(finalmillis / 1000);
      let dateObj = new Date(seconds * 1000); 
      hours = dateObj.getUTCHours(); 
      minutes = dateObj.getUTCMinutes(); 
      seconds = dateObj.getSeconds(); 
      this.timeString = hours.toString().padStart(2, '0') 
      + ':' + minutes.toString().padStart(2, '0') 
      + ':' + seconds.toString().padStart(2, '0'); 
      this.totaltimelist[i].totaltimeformat = this.timeString;
    }
  }
  calculateclosedtiming(){
    var firsttime;
    var lasttime;
    var hours;
    var minutes;
    for(let i=0;i<this.participant_list.length;i++){
      if(this.participant_list[i].timerlist.length != 0 && this.singledselist.cmd=="Ended"){
        firsttime = new Date(this.participant_list[i].timerlist[0].fromtime);
        lasttime = new Date(this.participant_list[i].timerlist[this.participant_list[i].timerlist.length-1].totime);
        var finalmillis = lasttime - firsttime;
        let seconds = Math.floor(finalmillis / 1000);
        let dateObj = new Date(seconds * 1000); 
        hours = dateObj.getUTCHours(); 
        minutes = dateObj.getUTCMinutes(); 
        seconds = dateObj.getSeconds(); 
        this.timeStrings_user = hours.toString().padStart(2, '0') 
        + ':' + minutes.toString().padStart(2, '0') 
        + ':' + seconds.toString().padStart(2, '0'); 
        this.participant_list[i].start_from=this.participant_list[i].timerlist[0].fromtime;
        this.participant_list[i].to_from=this.participant_list[i].timerlist[this.participant_list[i].timerlist.length-1].totime;
        this.participant_list[i].totaltimetaken = this.timeStrings_user;
      }
    }
  }
}