import { createReducer } from "redux-act";
import update from "immutability-helper";

import {
    Title,
    MusicState,
    setTitle,
    toggleMute,
    togglePlay,
    setSource,
} from "./types";

const defaultTitle: Title = {
    name: "Untitled",
    artist: "Unknown Artist",
    album: "Unknown Album",
    length: 0,
};

const initialState: MusicState = {
    muted: false,
    playing: false,
    title: defaultTitle,
    playTime: 0,
};

export const musicStateReducer = createReducer<MusicState>(
    {
        // @ts-expect-error - These appear to be working, even if functions
        // are technically prohibited, and were recommended upstream
        [setTitle]: (state: MusicState, title: Title): MusicState => {
            return update(state, {
                title: { $set: title },
            });
        },
        // @ts-expect-error - These appear to be working, even if functions
        // are technically prohibited, and were recommended upstream
        [togglePlay]: (state: MusicState): MusicState => {
            return update(state, { $toggle: ["playing"] });
        },
        // @ts-expect-error - These appear to be working, even if functions
        // are technically prohibited, and were recommended upstream
        [toggleMute]: (state: MusicState): MusicState => {
            return update(state, { $toggle: ["muted"] });
        },
        // @ts-expect-error - These appear to be working, even if functions
        // are technically prohibited, and were recommended upstream
        [setSource]: (state: MusicState, source: string): MusicState => {
            return update(state, { source: { $set: source } });
        },
    },
    initialState
);
