import { SaveState, SaveStateActions, LevelSaveState, MUTE_ALL, TOGGLE_MUSIC, TOGGLE_SOUNDS, SET_LEVEL_DONE, TOGGLE_SHOW_TIPS, setLevelDoneAction, SAVESTATE } from "./types";
import { levels } from "../../game/levels";
import { cloneDeep } from "lodash"


const getInitState = () => {
    let storedState = localStorage.getItem[SAVESTATE]
    if (storedState) {
        return JSON.parse(atob(storedState))
    }
    let levelStates = new Array<LevelSaveState>()
    for (let i = 0; i < levels.length; i++) {
        levelStates.push({ stars: 0, done: false })
    }
    return {
        levels: levelStates,
        playSounds: false,
        playMusic: false,
        showTips: true
    }
}

export const saveStateReducer = (state: SaveState = getInitState(), action: SaveStateActions) => {
    switch (action.type) {
        case MUTE_ALL:
            return reduceMuteAll(state);
        case TOGGLE_MUSIC:
            return reduceToggleMusic(state);
        case TOGGLE_SOUNDS:
            return reduceToggleSounds(state);
        case SET_LEVEL_DONE:
            return reduceSetLevelDone(state, action);
        case TOGGLE_SHOW_TIPS:
            return reduceToggleShowTips(state);
        default:
            return state;
    }
}

const reduceToggleMusic = (state: SaveState) => {
    return { ...state, playMusic: !state.playMusic }
}

const reduceToggleSounds = (state: SaveState) => {
    return { ...state, playSounds: !state.playSounds }
}

const reduceToggleShowTips = (state: SaveState) => {
    return { ...state, showTips: !state.showTips }
}

const reduceMuteAll = (state: SaveState) => {
    return { ...state, playSounds: false, playMusic: false }
}

const reduceSetLevelDone = (state: SaveState, action: setLevelDoneAction) => {
    let newLevelState = cloneDeep(state.levels)
    newLevelState[action.levelIdx] = { stars: action.stars, done: true }
    return { ...state, levels: newLevelState }
}
