import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import * as Parse from 'parse';
import {
  AlertController,
  IonicModule,
  LoadingController,
  ModalController,
  ToastController,
} from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { LiveComponent } from '../../../app/components/live/live.component';
import { LiveService } from '../../../services/live.service';
@Component({
  selector: 'app-link-page',
  templateUrl: './link-page.component.html',
  styleUrls: ['./link-page.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, LiveComponent, CommonModule],
})
export class LinkPageComponent implements OnInit {
  @ViewChild('live') live!: LiveComponent;
  currentUser?: Parse.Object = Parse.User.current(); //当前登录用户
  rid?: string;
  room?: Parse.Object;
  isFollow: boolean = false;
  showTool: boolean = true; // 是否显示工具栏
  // camera: boolean = false; //是否切换摄像头
  // mute: boolean = false; //是否静音
  constructor(
    public toastController: ToastController,
    private loadingCtrl: LoadingController,
    private alertController: AlertController,
    private activateRoute: ActivatedRoute,
    public liveService: LiveService
  ) {}

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      let rid: any = params.get('rid');
      this.rid = rid;
      if (!this.rid) {
        history.back();
        return;
      }
      this.refresh();
    });
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    this.getRoom();
    loading.present();
    loading.dismiss();
  }
  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('objectId', this.rid);
    query.notEqualTo('isDeleted', true);
    query.include('user');
    this.room = await query.first();
    this.getFollwState(this.room?.get('user').id);
  }
  /* 关注状态 */
  async getFollwState(uid: string) {
    let query = new Parse.Query('ProfileRadar');
    query.equalTo('toUser', this.currentUser?.id);
    query.equalTo('fromUser', uid);
    query.notEqualTo('isDeleted', true);
    query.equalTo('name', '关注');
    let r = await query.first();
    this.isFollow = r?.id ? true : false;
  }
  /* 关注 */
  async onCollection() {
    let query = new Parse.Query('ProfileRadar');
    query.equalTo('toUser', this.room?.get('user').id);
    query.equalTo('fromUser', this.currentUser?.id);
    // query.notEqualTo('isDeleted', true);
    query.equalTo('name', '关注');
    let profileRadar = await query.first();
    if (!profileRadar?.id) {
      let radar = Parse.Object.extend('ProfileRadar');
      profileRadar = new radar();
      profileRadar?.set('toUser', {
        __type: 'Pointer',
        className: '_User',
        objectId: this.room?.get('user').id,
      });
      profileRadar?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.currentUser?.get('company')?.id,
      });
      profileRadar?.set('fromUser', this.currentUser?.toPointer());
      profileRadar?.set('name', '关注');
    }
    profileRadar?.set('isDeleted', this.isFollow);
    await profileRadar?.save();
    this.isFollow = !this.isFollow;
  }
  /* 直播状态 */
  onChangeLiveStatus(e: any, type: string) {
    e.cancelBubble = true;
    switch (type) {
      case 'audio':
        this.liveService.updatePublishedAudioTrack();
        break;
      case 'camera':
        break;
      case 'mute':
        break;
    }
    // if (type == 'audio' || type == 'camera' || type == 'mute') {
    //   this.liveService.tools[type] = !this.liveService.tools[type];
    // }
  }
  /* 结束直播 */
  async endCall(e: any) {
    e.cancelBubble = true;
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '退出提示',
      message: '你确定退出登录吗？',
      buttons: [
        {
          text: '确定',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
            console.log('Confirm Cancel: blah');
            this.onExit();
          },
        },
        {
          text: '取消',
          handler: () => {},
        },
      ],
    });
    await alert.present();
  }
  onExit() {
    this.liveService.client.leave();
    history.back();
  }
}
