"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var immer_1 = require("immer");
/**
 * reducerWithImmer({})
 *  .case(actions.hoge, draft => {
 *    draft.fuga ++;
 *  })
 */
function reducerWithImmer(initialState) {
    var cases = {};
    var resets = [];
    var builder = {
        case: function (actionCreator, handler) {
            if (process.env.NODE_ENV !== 'production') {
                if (typeof actionCreator.type !== 'string') {
                    throw new Error("ActionCreator must has string member \"type\"");
                }
                if (actionCreator.type in cases) {
                    throw new Error(actionCreator.type + " is already set in reducer!");
                }
                if (typeof handler !== 'function') {
                    throw new Error("Invalid handler set with \"" + actionCreator.type + "\"");
                }
            }
            cases[actionCreator.type] = handler;
            return builder;
        },
        reset: function (actionCreator) {
            resets.push(actionCreator.type);
            return builder;
        },
        toReducer: function () {
            return function (state, action) {
                if (resets.includes(action.type)) {
                    return initialState;
                }
                var handler = cases[action.type];
                return handler
                    ? immer_1.default(state || initialState, function (draft) {
                        return handler(draft, action.payload);
                    })
                    : state || initialState;
            };
        }
    };
    return builder;
}
exports.reducerWithImmer = reducerWithImmer;
//# sourceMappingURL=reducerWithImmer.js.map