import { computed, nextTick, onMounted, onUpdated, ref } from "vue";

export function useChildLinkParent<T extends Record<string, any> = {}>(options: {
  getPositionExtra?: (index: number) => T,
  onClean?: () => void,
  onLengthChanged?: () => void,
}) {

  let currentIndex = 0;
  let length = 0;

  function getPosition() : { index: number } & Partial<T> {
    const index = currentIndex++;
    length++;
    return {
      index,
      ...(options.getPositionExtra?.(index) || {}) as T
    }
  }
  function resetCounter() {
    currentIndex = 0
  }

  onMounted(() => {
    resetCounter();
    options.onClean?.();
    nextTick(() => {
      options.onLengthChanged?.();
    })
  });
  onUpdated(() => {
    resetCounter();
    options.onClean?.();
    nextTick(() => {
      options.onLengthChanged?.();
    })
  });

  return {
    getLength: () => length,
    getPosition,
    resetCounter,
  }
}

export function useChildLinkChild(getPosition?: () => {
  index: number;
  [key: string]: unknown;
}|undefined) {

  const position = computed(() => getPosition?.()?.index ?? -1 );

  onMounted(() => {
    position.value;
  });
  onUpdated(() => {
    position.value;
  });

  return {
    position,
  }
}