import { ref, toRefs, watch } from '../../../../../adapter-vue';
import { CallMediaType, CallRole, CallStatus, TUIGlobal } from '../../../../../TUICallService';
import { useButtonPanelStatus, useCallInfoContext } from '../../../../hooks';
import { ButtonPanelConfig } from '../config';

export function useButtonPanelLayout() {
  const sortedLayout = ref([]);
  const buttonPanelConfig = ref([]);
  const { callStatus, isGroupCall, callType, callRole } = toRefs(useCallInfoContext());
  const { status: panelStatus } = useButtonPanelStatus() || {};

  watch([callStatus, isGroupCall, callType, callRole, panelStatus],
    () => {
      const key1 = TUIGlobal.isPC ? 'pc' : 'mobile';
      const key2 = isGroupCall.value ? 'groupCall' : 'singleCall';
      const key3 = callType.value === CallMediaType.AUDIO ? 'audio' : 'video';
      // eslint-disable-next-line no-nested-ternary
      let key4 = callStatus.value === CallStatus.CALLING
        ? callRole.value === CallRole.CALLER ? 'calling' : 'accept'
        : callStatus.value;
      
      if (isGroupCall && panelStatus?.value === 'close') {
        key4 = 'close_' + key4;
      }

      const config = ButtonPanelConfig?.[key1]?.[key2]?.[key3]?.[key4] || [];
      buttonPanelConfig.value = config;
      const layout = [];
      let index = 0;

      for (let i = 0; i < config.length; i++) {
        const width = 12 / config[i].length;
        const height = 3;
    
        for (let j = 0; j < config[i].length; j++) {
          layout[index++] = {
            i: config[i][j].name,
            x: j * width,
            y: i * width,
            w: width,
            h: height,
            // @ts-ignore
            customStyle: config[i][j].customStyle,
          };
        }
      }

      index = 0;
      let rs = [];
      for (let i = 0; i < config.flat().length; i++) {
        rs[i] = layout[index++];
      }

      rs = rs.filter(item => item.i);
      sortedLayout.value = rs;
    }, {
      immediate: true,
    });
  return { layout: sortedLayout, config: buttonPanelConfig } as const;
}
