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>(
    {
        [setTitle]: (state: MusicState, title: Title): MusicState => {
            return update(state, {
                title: { $set: title },
            });
        },
        [togglePlay]: (state: MusicState): MusicState => {
            return update(state, { $toggle: ["playing"] });
        },
        [toggleMute]: (state: MusicState): MusicState => {
            return update(state, { $toggle: ["muted"] });
        },
        [setSource]: (state: MusicState, source: string): MusicState => {
            return update(state, { source: { $set: source } });
        },
    },
    initialState
);
