"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var redux_observable_1 = require("redux-observable");
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var typescript_fsa_1 = require("typescript-fsa");
var selection_1 = require("../utils/selection");
var reducerWithImmer_1 = require("./reducerWithImmer");
var typescript_fsa_redux_observable_1 = require("./typescript-fsa-redux-observable");
var pagesEndpoint = 'https://tile.hackforplay.xyz/pages.json';
var nope = {
    index: -1,
    src: 'https://tile.hackforplay.xyz/nope.png',
    placement: {
        type: 'Nope'
    },
    author: {
        name: 'nope'
    }
};
var actionCreator = typescript_fsa_1.default('react-map-editor/palette');
exports.actions = {
    loadPages: actionCreator.async('LOAD_PAGES'),
    setSelection: actionCreator('SET_SELECTION'),
    setCursorMode: actionCreator('SET_CURSOR_MODE')
};
var initialState = {
    pages: [],
    selection: null,
    nib: [[]],
    cursorMode: 'nope'
};
exports.default = reducerWithImmer_1.reducerWithImmer(initialState)
    .case(exports.actions.setSelection, function (draft, payload) {
    draft.selection = payload;
    if (payload) {
        // Update nib
        var page_1 = draft.pages.find(function (page) { return page.index === payload.page; });
        draft.nib = selection_1.getMatrix(payload).map(function (row) {
            return row.map(function (num) {
                if (!page_1)
                    return nope;
                return page_1.tiles[num] || nope;
            });
        });
        draft.cursorMode = 'pen';
    }
})
    .case(exports.actions.setCursorMode, function (draft, payload) {
    // nib がセットされていないとペンモードにはならない
    if (payload === 'pen' && draft.nib[0].length < 1)
        return;
    draft.cursorMode = payload;
})
    .case(exports.actions.loadPages.done, function (draft, payload) {
    draft.pages = Object.values(payload.result.pages);
})
    .toReducer();
exports.epics = redux_observable_1.combineEpics(function (action$) {
    return action$.pipe(typescript_fsa_redux_observable_1.ofAction(exports.actions.loadPages.started), operators_1.take(1), operators_1.mergeMap(function (action) {
        return rxjs_1.from(fetch(pagesEndpoint).then(function (response) { return response.json(); })).pipe(operators_1.map(function (result) {
            return exports.actions.loadPages.done({ params: action.payload, result: result });
        }), operators_1.catchError(function (error) {
            return rxjs_1.of(exports.actions.loadPages.failed({ params: action.payload, error: error }));
        }));
    }));
});
//# sourceMappingURL=palette.js.map