import type { Track } from "@applets/core/types.js";
import type { State } from "./types";
import { expose } from "@scripts/common.ts";

////////////////////////////////////////////
// ACTIONS
////////////////////////////////////////////
const actions = expose({
  add,
  fill,
  shift,
  unshift,
});

export type Actions = typeof actions;

// Actions

function add(state: State, items: Track[]): State {
  return { ...state, future: [...state.future, ...items] };
}

// TODO: Shuffle, limit track amount, etc.
function fill(state: State, availableItems: Track[]): State {
  state = add(state, availableItems);

  // Automatically insert track if there isn't any
  if (!state.now) return shift(state);
  return state;
}

function shift(state: State): State {
  const now = state.future[0] || null;
  const future = state.future.slice(1);
  const past = state.now ? [...state.past, state.now] : state.past;

  return { past, now, future };
}

function unshift(state: State): State {
  if (state.past.length === 0) return state;

  const past = [...state.past];
  const [last] = past.splice(past.length - 1, 1);
  const now = last ?? null;
  const future = state.now ? [state.now, ...state.future] : state.future;

  return { past, now, future };
}
