import { navigateTo, redirectTo, setKeepScreenOn, showToast } from "@tarojs/taro";
import { useCallCenter } from "any-hooks/communication/useCallCenter";
import { onMounted, watch } from "vue";
import { useInjector } from "vue-vulcan";
import { useAppInitInfo } from "../common/useAppInitInfo";


/** 在小程序平台监听远程联系人的呼叫动作 */
export function useCallerListener() {
  const { caller, target, myCallState, answerCaller } = useInjector(useCallCenter);
  const { checkCamearSetting } = useInjector(useAppInitInfo);

  onMounted(() => {
    /** 保持屏幕常亮  */
    onMounted(() => setKeepScreenOn({keepScreenOn: true}));
  })

  watch(caller, current => {      
    if(!current) return;  
    switch(current.action) {
      case 'Request':
      break;
      case 'Hangup':         
      console.log('对方挂断') 
        showToast({title: '对方已取消呼叫', icon: 'none'});
      break;
    }  
  })

  watch(target, val => {
    console.log('呼叫目标的action', val)
    switch(val?.action) {
      case 'Busying':
        showToast({title: '对方繁忙，暂时无法接受呼叫', icon: 'none'});
      break;
      case 'Hangup':
        console.log('对方挂断') 
        showToast({title: '对方拒绝了您的呼叫', icon: 'none'});
      break;
    }
  })

  // 根据用户的呼叫状态变化，执行相应的页面跳转逻辑
  watch(myCallState, (state, prev) => {
    switch(state) {
      case 'callout':
        if(prev !== 'idle') {
          showToast({title:'已发出呼叫，等待对方回应...', icon:'none'});          
        }else {
          navigateTo({url: '/pages/calling/index'});
        }        
      break;
      case 'callin':
        checkCamearSetting().then(r => {
          r ? navigateTo({url: '/pages/calling/index'}) : answerCaller('NoDevice')
        })        
      break;          
      case 'calling':    
        redirectTo({url: '/pages/meeting/index'});
      break;    
    }
  })
}