import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { AuthserviceService } from 'src/app/authservice.service';
import { ServicesService } from 'src/app/services.service';
import { ChattingService } from 'src/app/services/chatting/chatting.service';
import { WebsocketService } from 'src/app/services/websocket.service';

@Component({
  selector: 'app-startconference',
  templateUrl: './startconference.component.html',
  styleUrls: ['./startconference.component.scss']
})
export class StartconferenceComponent implements OnInit {
  event_id: any;
  user_id: any;
  event_name: any
  constructor(public service: ServicesService, public socket: WebsocketService, public ActiveRoute: ActivatedRoute, public spinner: NgxSpinnerService, public chatService: ChattingService, public auth: AuthserviceService, public router: Router,) {
    this.ActiveRoute.params.subscribe(async (params) => {
      try {
        var data = JSON.parse(atob(decodeURIComponent(params['id'])));
        this.event_id = data.id;
        this.user_id = data.user_id;
        this.event_name = data.event_name;
      } catch (error) {
      }
    });
  }

  async ngOnInit(): Promise<void> {
    sessionStorage.removeItem('clearInterval')
    this.SocketConnect();
    let me = this;
    me.getMeetingById(me.event_id, me.user_id)
    setTimeout(() => {
      me.socket.OnMessage().subscribe(async (result) => {
        let data = JSON.parse(result);
        if (data.message != undefined) {
          if (data.message == "Next Question.") {
            me.getMeetingById(me.event_id, me.user_id)
          }
        }
      })
    }, 1000);
    setInterval(async () => {
      if (sessionStorage.getItem('clearInterval') == null || sessionStorage.getItem('clearInterval') == undefined) {
        await this.CheckMeetingStart()
      }
    }, 15000)
  }
  async getMeetingById(id, AttendeeId) {
    this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      }
      else {
        var token = session
        await this.chatService.getMeetingById(id, token).then(async (result) => {
          var list = JSON.parse(<string>result[0].json);
          if (result[0].status == 200) {
            if (list.data.is_live == 1 && list.data.meeting_id != '') {
              sessionStorage.setItem('clearInterval', 'true')

              let meeting_id = list.data.meeting_id;
              let user_id = this.user_id
              let att_array = list.data.attendees ? JSON.parse(list.data.attendees) : [];
              let att_id = att_array.filter(x => x.U == user_id)
              let attendee_id = "";
              if (att_id.length > 0) {
                attendee_id = att_id[0].A
              }
              this.service.addAttendee(meeting_id, attendee_id, user_id).then(async (result) => {
                var list = JSON.parse(<string>result[0].json);
                if (list.status == 200) {
                  var meeting = {
                    AttendeeId: list.data.attendee.Attendee.AttendeeId,
                    meeting_id: this.event_id
                  }
                  this.router.navigate([`/conference/` + encodeURIComponent(btoa(JSON.stringify(meeting)))]);
                }
              })
            }
          }
          this.spinner.hide();

        })
      }
    })
  }
  async SocketConnect() {
    var userId = parseInt(localStorage.getItem('CisspUserId'));
    let MessageArr = {
      action: 'message',
      msg: {
        action: 'connected',
        user_id: userId,
        test_id: 1,
        roll_id: 3,
        q_id: 1,
        sr_no: 1,
      },
    };
    this.socket.Connect();
    this.socket.OnOpen().then((result) => {
      this.socket.DoSend(MessageArr).then((result) => {

      }).catch((err) => { });
    }).catch((err) => { });
  }


  async CheckMeetingStart() {

    this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      }
      else {
        var token = session
        await this.chatService.getMeetingById(this.event_id, token).then(async (result) => {
          var list = JSON.parse(<string>result[0].json);
          if (result[0].status == 200) {
            if (list.data.is_live == 1) {
              this.getMeetingById(this.event_id, this.user_id);
            }
          }
          this.spinner.hide();

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