import { ref, watch } from "vue";

export function useColumns(source: any[]) {
  const _raw = source;
  let isReset = false;

  const columns = ref([..._raw]);

  const _action = _raw[_raw.length - 1];

  const _fixed = _raw.slice(0, 2);

  const displayColumns = ref<string[]>([
    ..._raw.map(({ prop }) => prop).filter(p => p)
  ]);

  function reset() {
    isReset = true;
    displayColumns.value = [..._raw.map(({ prop }) => prop).filter(p => p)];
  }

  function fixed(placement: "left" | "right", index: number) {
    columns.value[index].fixed = placement;
  }

  watch(
    () => displayColumns.value,
    cols => {
      const currentColumns = _raw
        .filter(({ prop }) => cols.includes(prop))
        .map(col => ({ ...col, fiexed: isReset ? "" : col.fixed }));
      columns.value = [..._fixed, ...currentColumns, _action];
      isReset = false;
    }
  );

  return {
    _raw,
    fixed,
    reset,
    columns,
    displayColumns
  };
}
