import { Pen } from '@meta2d/core';
import { getter } from '@meta2d/core/src/utils/object';
import { reactive } from 'vue';

export enum SelectionMode {
  File,
  Pen,
  Pens,
  Fit // 布局模式
}

const selections = reactive<{
  mode: SelectionMode;
  pen?: Pen;
  pens?: Pen[];
  fit?: any;
}>({
  // 选中对象类型：0 - 画布；1 - 单个图元；2 - 多选
  mode: SelectionMode.File,
  pen: undefined,
  pens: undefined,
});

export const useSelection = () => {
  const select = (pens?: Pen[], fit?: any) => {
    if (fit) {
      selections.mode = SelectionMode.Fit;
      selections.pen = undefined;
      selections.pens = undefined;
      selections.fit = fit;
      return;
    }else{
      selections.fit = undefined;
    }
    if (!pens || !pens.length) {
      selections.mode = SelectionMode.File;
      selections.pen = undefined;
      selections.pens = undefined;
      return;
    }

    if (pens.length > 1) {
      selections.mode = SelectionMode.Pens;
      selections.pen = undefined;
      selections.pens = pens;
    } else {
      selections.mode = SelectionMode.Pen;
      selections.pen = pens[0];
      // @ts-ignore
      let props = selections.pen.props?.custom || [];
      let realTimes = selections.pen.realTimes || [];
      for(let i = 0;i<props.length;i++){
        let propKey = props[i].key || ''
        if(propKey.includes('.')){
          selections.pen[propKey] = getter(pens[0],propKey) // 根本原因 setValue会删除pen[0]的propKey，所以重新赋值
        }
      }
      for(let i = 0;i<realTimes.length;i++){
        let realTime = realTimes[i].key || ''
        if(realTime.includes('.')){
          selections.pen[realTime] = getter(pens[0],realTime) // 根本原因 setValue会删除pen[0]的propKey，所以重新赋值
        }
      }
        selections.pens = undefined;
    }
  };
  return {
    selections,
    select,
  };
};
