"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateScene = exports.editWithCursor = void 0;
var immer_1 = require("immer");
var lodash_es_1 = require("lodash-es");
/**
 * カーソルに応じた変更をマップに加える
 * immer を使うことで変更の履歴を生成する
 * 変更がない場合は履歴を追加しない
 */
function editWithCursor(editing, cursor) {
    var invertPatches = [];
    var next = immer_1.default(editing.sceneMap, function (draft) {
        var e_1, _a, e_2, _b, e_3, _c;
        var tables = draft.tables, squares = draft.squares;
        if (!cursor.nib || !Array.isArray(tables))
            return;
        var bottom = tables.length - 1; // 最下層のレイヤー
        var height = tables && tables[0].length;
        var width = tables && tables[0] && tables[0][0].length;
        if (cursor.mode === 'pen') {
            try {
                for (var _d = __values(cursor.nib.entries()), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var _f = __read(_e.value, 2), y = _f[0], row = _f[1];
                    var _loop_1 = function (x, tile) {
                        if (tile.placement.type === 'Nope')
                            return "continue"; // skip
                        var X = cursor.x + x;
                        var Y = cursor.y + y;
                        var contains = 0 <= X && X < width && 0 <= Y && Y < height;
                        if (!contains)
                            return "continue"; // 領域外
                        // 上のレイヤーから塗っていく. 既存のレイヤーを下にずらし, FIFO.
                        if (tables[0][Y][X] === tile.index)
                            return "continue"; // 同じタイル
                        for (var layer = bottom; layer > 0; layer--) {
                            var above = tables[layer - 1][Y][X];
                            if (above > 0) {
                                tables[layer][Y][X] = above;
                            }
                        }
                        tables[0][Y][X] = tile.index;
                        // add tile info
                        if (squares.every(function (s) { return s.index !== tile.index; })) {
                            squares.push({
                                index: tile.index,
                                placement: tile.placement,
                                tile: {
                                    size: [32, 32],
                                    image: {
                                        type: 'url',
                                        src: tile.src
                                    },
                                    author: tile.author
                                }
                            });
                        }
                    };
                    try {
                        for (var _g = (e_2 = void 0, __values(row.entries())), _h = _g.next(); !_h.done; _h = _g.next()) {
                            var _j = __read(_h.value, 2), x = _j[0], tile = _j[1];
                            _loop_1(x, tile);
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
        if (cursor.mode === 'eraser') {
            try {
                for (var _k = __values(tables.values()), _l = _k.next(); !_l.done; _l = _k.next()) {
                    var table = _l.value;
                    var tableRow = table && table[cursor.y];
                    var index = tableRow && tableRow[cursor.x];
                    if (index > -1) {
                        tableRow[cursor.x] = -1;
                        break;
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_l && !_l.done && (_c = _k.return)) _c.call(_k);
                }
                finally { if (e_3) throw e_3.error; }
            }
        }
    }, function (_, _invertPatches) {
        invertPatches.push.apply(invertPatches, __spread(_invertPatches));
    });
    return {
        sceneMap: next,
        undoPatches: mergeUndoPatches(editing.undoPatches, invertPatches, cursor.dragId)
    };
}
exports.editWithCursor = editWithCursor;
exports.updateScene = function (scene, cursor) {
    var sceneMap = editWithCursor({ sceneMap: scene.map, undoPatches: [] }, cursor).sceneMap;
    return sceneMap === scene.map ? scene : __assign(__assign({}, scene), { map: sceneMap });
};
function mergeUndoPatches(undoPatches, invertPatches, dragId) {
    if (invertPatches.length === 0) {
        return undoPatches; // 変更がない
    }
    var lastUndo = lodash_es_1.last(undoPatches);
    if (dragId === undefined || !lastUndo || lastUndo.dragId !== dragId) {
        // ユニットを追加
        return undoPatches.concat({
            dragId: dragId,
            patches: invertPatches
        });
    }
    // 末尾のユニットにパッチを追加
    return undoPatches.slice(0, undoPatches.length - 1).concat({
        dragId: dragId,
        patches: lastUndo.patches.concat(invertPatches)
    });
}
//# sourceMappingURL=updateScene.js.map