import { watch, ref, toRefs } from '../../adapter-vue';
import { useCustomUI } from './useCustomUI';
import { TUIGlobal } from '../../TUICallService';
import { add, deepClone, findValues, modify } from '../util';
import { VirtualBackgroundMobileConfig } from '../components/common/ButtonPanel/config/VirtualBackgroundMobileConfig';
import { useCallInfoContext } from './useCallInfoContext';
import { ButtonPanelConfig } from '../components/common/ButtonPanel/config/InitConfig';

function setVirtualBackgroundConfig(config) {
  const newConfig = deepClone(config);
  modify(newConfig, 'mobile.singleCall.video', VirtualBackgroundMobileConfig);
  add(newConfig, 'pc.singleCall.video.calling[0][2]', { name: 'virtualBackground' });
  add(newConfig, 'pc.singleCall.video.accept[0][1]', { name: 'virtualBackground' });
  add(newConfig, 'pc.singleCall.video.connected[0][3]', { name: 'virtualBackground' });
  add(newConfig, 'pc.groupCall.video.calling[0][3]', { name: 'virtualBackground' });
  add(newConfig, 'pc.groupCall.video.connected[0][4]', { name: 'virtualBackground' });
  return newConfig;
}

export function useCustomUIButtonConfig() {
  const { isShowEnableVirtualBackground } = toRefs(useCallInfoContext());
  const customUIConfig = useCustomUI();
  const results = ref([]);

  watch([customUIConfig, isShowEnableVirtualBackground], () => {
    let initConfig = deepClone(ButtonPanelConfig);
    if (isShowEnableVirtualBackground.value && !TUIGlobal.isH5) {
      initConfig = setVirtualBackgroundConfig(ButtonPanelConfig);
    }

    const { button: buttonsConfig } = customUIConfig.value;
    const rs = [];
    function condition(value) {
      return Object.keys(buttonsConfig).includes(value);
    }

    function formatResults({ key, value }) {
      const valueArr = value.split('.');
      let path = valueArr.slice(0, valueArr.length - 1);
      const rowPath = valueArr.slice(0, valueArr.length - 2);
      const rowIndex = rowPath[rowPath.length - 1];
      if (rowIndex === '0') {
        for(let i = 0; i < 3; i++) {
          let newPath = rowPath.slice();
          newPath.push(i);
          newPath.push('customStyle');
          newPath.push('justifyContent');
          newPath = newPath.join('.');
          rs.push({ path: newPath, value: 'center' });
        }
      }
      
      path.push('props');
      path.push('show');
      path = path.join('.');
      return {
        path,
        value: buttonsConfig?.[key],
      };
    }
  
    findValues(initConfig, condition, '', rs, formatResults);
    rs?.forEach((item) => {
      modify(initConfig, item.path, item.value);
    });
    results.value = initConfig;
  }, {
    immediate: true,
  });

  return results;
}
