import { Component, OnInit ,ViewChild, Output, EventEmitter, AfterViewInit, ChangeDetectorRef} from '@angular/core';
import * as moment from 'moment';
import { HyperService } from '../../core/services/http.service';
import { Router } from "@angular/router";
import { LocalStorage } from '../../core/services/local_storage.service';
// import RtmClient from './rtm-client';
import RtmClient from 'assets/js/rtm-client.js';
import { Toast,validator,serializeFormData } from 'assets/js/common.js';
import { MyschedulesDetailsComponent } from '../myschedule-details/myschedule-details.component';
import { CONFIG } from 'app/config';
import { Observable } from 'rxjs/Observable';
import { ToasterService } from '../../core/services/toaster.service';
import { clearInterval } from 'timers';
declare var $: any;

@Component({
  selector: 'app-hoschedule',
  templateUrl: './hoschedule.component.html',
  styleUrls: ['./hoschedule.component.scss']
})
export class HoSchedulesComponent implements OnInit {

  @ViewChild(MyschedulesDetailsComponent) content_modal: MyschedulesDetailsComponent;
  loader: boolean;
  bullet_in: any;
  sales_date: any;
  user_dashboard: any;
  percentage: any;
  user_role:any;
  show_dashboard_dse: boolean=false;
  // rtm = new RtmClient();
  accountname: any;
  account_appId: string;
  channelname: any;
  msgcollection: any=[];
  today = new Date();
  channelargs: any;
  modifiedjson: string;
  isaccount_broadcast: boolean = false;
  rolename: any;
  empcode: any;
  emp_name: any;
  timerVar: any;
  ticks =0;

  total_item: number;
  page_per_size: number = 10;
  current_page: number;
  total_page: number;
  activePage: number = 1;
  page_count: number;
  activeItem: number = -1;
  interval_time:any;
  constructor(private server: HyperService,private toaster: ToasterService, private router: Router,private cd: ChangeDetectorRef) {
    if (LocalStorage.getValue('user_data') != undefined){
        this.user_role = LocalStorage.getValue('user_data').role;
    }
  }
 
  ngOnInit() { 
    this.rolename = LocalStorage.getValue('user_data').role;
    this.isaccount_broadcast = this.rolename == 3 ? true : false;
    this.current_page = 0;
    this.activePage = 0;
    this.getTrainingList(this.activePage);
    this.rtminitalization();
  }
  
  rtminitalization(){
    CONFIG.rtm.on('ConnectionStateChanged', (newState, reason) => {
      if (newState === 'ABORTED') {
        if (reason === 'REMOTE_LOGIN') {
          Toast.error('You have already been kicked off!')
          // $('#accountName').text('Agora Chatroom')
          // this.rtm.clearState()
          $('#dialogue-list')[0].innerHTML = ''
          $('#chat-message')[0].innerHTML = ''
        }
      }
    })
  
    CONFIG.rtm.on('MessageFromPeer', (message, peerId) => {
    })
  
    CONFIG.rtm.on('MemberJoined', ({ channelName, args }) => {
      this.channelargs = args;
    })
  
    CONFIG.rtm.on('MemberLeft', ({ channelName, args }) => {
    })
  
    CONFIG.rtm.on('ChannelMessage', ({ channelName, args }) => {
      const [message, memberId] = args;
    })
  }

  rtmlogin(list){
    // clearInterval(this.interval_time)
    this.empcode = LocalStorage.getValue('user_data').emp_code;
    this.emp_name = LocalStorage.getValue('user_data').fname !='' && LocalStorage.getValue('user_data').fname !=undefined && LocalStorage.getValue('user_data').fname != null ? LocalStorage.getValue('user_data').fname : LocalStorage.getValue('user_data').lname !='' && LocalStorage.getValue('user_data').lname !=undefined && LocalStorage.getValue('user_data').lname != null ? LocalStorage.getValue('user_data').lname : '#';
    this.accountname = this.empcode+'_'+this.emp_name.replace(/ +/g, "");
    this.account_appId ='1fabd779cd5a4a2abbfc13aec37c5a35';
    if(!CONFIG.rtm._logined) {
      try {
        CONFIG.rtm.init(this.account_appId)
        // window.rtm = rtm
        CONFIG.rtm.login(this.accountname, '').then(() => {
          CONFIG.rtm._logined = true;
          this.loader = false;
          this.channelname = list.channel;
      this.content_modal.showcontentrModalchat('Result',CONFIG.rtm,list, (data) => { 
        this.interval_time = setInterval(() => {
          this.getTraining(this.activePage);
        }, 1000*300)
      })
        }).catch((err) => {
        })
      } catch (err) {
        console.error(err)
      }
    }else{
      this.toaster.show('Wait few min..');
      this. rtmlogin(list);
    }
  }

  getTraining(page:number = 0){
    this.server.get("videotraining/scheduletraining?page="+page+"&limit=10")
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed' && data.result.data != null  ) {
        this.bullet_in = data.result.data;
        this.total_item = Number(data.result.total);
        this.datechecking();
        this.isBroadcaster();
      } else if (data.result.status == 401 && data.result.response == 'failed') {
        this.router.navigateByUrl('');
      }
  });
  }
    
  getTrainingList(page: number = 0) {
    this.loader = true
    //this.server.get("common/learning")
    this.server.get("videotraining/scheduletraining?page="+page+"&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.total_item = Number(data.result.total);
          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;
      }
      if(this.bullet_in[i].status == 2){
        this.bullet_in[i].cmd = 'Ended';
        this.bullet_in[i].btnstatus = false;
      }else{
        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';
          this.bullet_in[i].btnstatus = false;
        }else{
          this.bullet_in[i].cmd = 'Join';
        }
      }
    }
    
    this.timerVar = Observable.interval(1000).subscribe(x => {
      this.demotimer();
    });
  }

  demotimer(){
    var today:any = new Date();
    if(this.isaccount_broadcast){
      var startdate = new Date();
      var durationInMinutes = 5;
      startdate.setMinutes(startdate.getMinutes() + durationInMinutes);
      for(let i=0;i<this.bullet_in.length;i++){
        if(this.bullet_in[i].status == 2){
          this.bullet_in[i].cmd = 'Ended';
          this.bullet_in[i].btnstatus = false;
        }else{
          if(new Date(this.bullet_in[i].fromdate) > startdate){
            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';
            this.bullet_in[i].btnstatus = false;
          }else{
            this.bullet_in[i].cmd = 'Join';
          }
        }
      }
    }else{
      for(let i=0;i<this.bullet_in.length;i++){
        if(this.bullet_in[i].status == 2){
          this.bullet_in[i].cmd = 'Ended';
          this.bullet_in[i].btnstatus = false;
        }else{
          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';
            this.bullet_in[i].btnstatus = false;
          }else{
            this.bullet_in[i].cmd = 'Join';
          }
        }
      }
    }   
  }

  isBroadcaster(){
    this.accountname = LocalStorage.getValue('user_data').emp_code;
    for(let i=0;i<this.bullet_in.length;i++){
      if(this.accountname == this.bullet_in[i].organiser){
        this.bullet_in[i].broadcaster = true;
      }else{
        this.bullet_in[i].broadcaster = false;
      }
    }
  }

  onSelect(list) {
    let brower_name;
    let navi_name = window.navigator.userAgent.toLowerCase();
    if(navi_name.indexOf('chrome') > -1){
      brower_name = 'Chrome';
      this.rtmlogin(list);
    }else if(navi_name.indexOf('firefox') > -1){
      brower_name = 'Mozilla Firefox';
      this.showalert(brower_name);
    }else if(navi_name.indexOf('safari') > -1){
      brower_name = 'Safari';
      this.showalert(brower_name);
    }else if(navi_name.indexOf('trident') > -1){
      brower_name = 'Microsoft Internet Explorer';
      this.showalert(brower_name);
    }else if(navi_name.indexOf('edge') > -1){
      brower_name = 'Microsoft Edge';
      this.showalert(brower_name);
    }else if(navi_name.indexOf('opr') > -1 || navi_name.indexOf('opera') > -1){
      brower_name = 'Opera';
      this.showalert(brower_name);
    }else{
      this.showalert('Unknown');
    }
    
  }

  showalert(b_name){
    alert(b_name +' not supported for i-Learn conference, use Chrome browser.')
  }

  onpopup(list,index){
    let sendData:any=list;
    this.content_modal.showpopupmodal('Result', sendData,index, (data) => {
      this.getTrainingList(this.activePage);
    })
  }

  deleteRow(id){
    this.content_modal.showdeletepopupmodal('Result', id,(data) => {
      this.getTrainingList(this.activePage);
    })
  }

  addtraining(){
    this.router.navigateByUrl('hoaddtraining');
  }

  public getServerData(event) {
    this.page_count = (event - 1);
    this.getTrainingList(this.page_count)
    this.onPageChange(event);
  }

  public onPageChange(event) {
    this.activeItem = -1;
    this.activePage = event;
  }

}