import { markRaw, shallowRef, computed } from 'vue';

import type {
  TimeLabel, TimeLabelStoreMutationOp,
} from '../sharedworker/datastores/timelabelstore';
import type { useDatabase } from './database';
import { comparerByKey } from '../common/utils';


export type { TimeLabel };

export function timeLabelOrdering(timeLabel: TimeLabel) {
  return timeLabel.label;
}

export function useTimeLabelStore(database: ReturnType<typeof useDatabase>) {
  const timeLabels = shallowRef<TimeLabel[]>([]);

  async function mutate(ops: TimeLabelStoreMutationOp[]) {
    return await database.mutate('timeLabel', ops);
  }

  async function load() {
    timeLabels.value = (await database.query('timeLabel', {}) as any).map(x => ({
      id: x.id, label: x.label,
      startTime: markRaw(x.startTime), endTime: markRaw(x.endTime),
      disabled: x.disabled,
    }));
  }

  return { timeLabels: computed(
    () => timeLabels.value.sort(comparerByKey(timeLabelOrdering))
  ), mutate, load };
}

export type TimeLabelStore = Awaited<ReturnType<typeof useTimeLabelStore>>;
