import { Component, EventEmitter, OnInit, Output, output } from '@angular/core';
import { FormsModule } from '@angular/forms';
import * as Parse from 'parse';
import {
  AlertController,
  IonicModule,
  LoadingController,
  ToastController,
} from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { AiChatService } from '../../../services/aichart.service';
import { HttpService } from '../../../services/http.service';
import { LiveService } from '../../../services/live.service';
@Component({
  selector: 'app-live',
  templateUrl: './live.component.html',
  styleUrls: ['./live.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule],
})
export class LiveComponent implements OnInit {
  @Output() touch = new EventEmitter();
  profile?: Parse.Object;
  rid?: string;
  room?: Parse.Object;
  changeScreen: boolean = false; //大小屏切换
  timer: any;//轮询获取频道token的定时
  constructor(
    public toastController: ToastController,
    private loadingCtrl: LoadingController,
    private activateRoute: ActivatedRoute,
    private alertController: AlertController,
    private http: HttpService,
    private liveService: LiveService
  ) {
    this.liveService.initAgora()
  }

  ngOnInit() {
    this.liveService.getDevices();
    this.activateRoute.paramMap.subscribe(async (params) => {
      let rid: any = params.get('rid');
      this.rid = rid;
      if (!this.rid) {
        return;
      }
      this.getRoom();
    });
  }

  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('objectId', this.rid);
    query.notEqualTo('isDeleted', true);
    query.include('user', 'profile');
    this.room = await query.first();
    // let queryProfile = new Parse.Query('Profile');
    // queryProfile.equalTo('user', this.room?.get('user').id);
    // queryProfile.notEqualTo('isDeleted', true);
    // this.profile = await queryProfile.first();
    if (this.room?.id) {
      await this.liveService.getToken(this.room);
    } else {
      const alert = await this.alertController.create({
        header: '提示',
        message: '房间号不存在',
        buttons: ['Action'],
      });
      await alert.present();
    }
  }
  /* 监听屏幕切换 */
  onChangeScreen(type: string, e: any) {
    if (type == 'big' && this.changeScreen) {
      e.cancelBubble = true;
      this.changeScreen = !this.changeScreen;
    } else if (type == 'small' && !this.changeScreen) {
      e.cancelBubble = true;
      this.changeScreen = !this.changeScreen;
    }
  }
  onTouch() {
    this.touch.emit();
  }
  ngOnDestroy(): void {
    /* 离开房间 */
    this.liveService.client.leave();
    console.log(111);
  }
}
