import { writable } from 'svelte/store';

export const UNCHECKED = 0;
export const CHECKED = 1;
export const WEIRD = 2;

export function createTriState(initialValue) {
    const { subscribe, set } = writable(initialValue);

  return {
    subscribe,
    setUnchecked: () => set(UNCHECKED),
    setWeird: () => set(WEIRD),
    setChecked: () => set(CHECKED),
    set
  }
}

export function createTriStates(initialValue, length) {
  const { subscribe, update, set } = writable(Array.from({length}, e => initialValue));

  const setAt = (index, newValue) => {
      update(array => [...array.slice(0, index), newValue, ...array.slice(index + 1)]);
  };

  return {
    subscribe,
    set,
    setAt,
    length,
    storeAt: index => {
      const set = value => setAt(index, value);
      return {
        subscribe: fun => subscribe(subvalues => fun(subvalues[index])),
        set,
        setUnchecked: () => set(UNCHECKED),
        setWeird: () => set(WEIRD),
        setChecked: () => set(CHECKED)
      };
    },
    updateAll: fun => {
      update(array => array.map(fun));
    }
  }
}
      
