"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.baseSelectionState = exports.preloadNibState = exports.cursorState = exports.editingState = exports.undoPatchesState = exports.sceneState = exports.sceneScreenState = exports.sceneMapState = exports.debugState = exports.paletteNibState = exports.paletteSelectionState = exports.palettePagesState = exports.cursorModeState = void 0;
var next_1 = require("@hackforplay/next");
var recoil_1 = require("recoil");
var selection_1 = require("../utils/selection");
var updateBase_1 = require("../utils/updateBase");
var pagesEndpoint = 'https://tile.hackforplay.xyz/pages.json';
/**
 * パレットが選択されていない状態ではペンにしないこと
 * パレットが選択されたらペンに変更すること
 */
exports.cursorModeState = recoil_1.atom({
    key: 'cursorModeState',
    default: 'nope'
});
exports.palettePagesState = recoil_1.selector({
    key: 'palettePageState',
    get: function () { return __awaiter(void 0, void 0, void 0, function () {
        var response, result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, fetch(pagesEndpoint)];
                case 1:
                    response = _a.sent();
                    return [4 /*yield*/, response.json()];
                case 2:
                    result = _a.sent();
                    return [2 /*return*/, Object.values(result.pages)];
            }
        });
    }); }
});
exports.paletteSelectionState = recoil_1.atom({
    key: 'paletteSelectionState',
    default: null
});
exports.paletteNibState = recoil_1.selector({
    key: 'paletteNibState',
    get: function (_a) {
        var get = _a.get;
        return __awaiter(void 0, void 0, void 0, function () {
            var selection, pages, page, matrix, nib;
            return __generator(this, function (_b) {
                selection = get(exports.paletteSelectionState);
                if (!selection)
                    return [2 /*return*/, [[]]]; // 空のペン先
                pages = get(exports.palettePagesState);
                page = pages.find(function (page) { return page.index === selection.page; });
                matrix = selection_1.getMatrix(selection);
                nib = matrix.map(function (row) {
                    return row.map(function (num) {
                        var tile = page === null || page === void 0 ? void 0 : page.tiles[num];
                        if (!tile) {
                            var info = JSON.stringify(selection);
                            throw new Error("Tile not found: " + info);
                        }
                        return tile;
                    });
                });
                return [2 /*return*/, nib];
            });
        });
    }
});
exports.debugState = recoil_1.atom({
    key: 'debugState',
    default: true
});
/**
 * 初期値が設定されるまで loading
 */
exports.sceneMapState = recoil_1.atom({
    key: 'sceneMapState',
    default: new Promise(function () { })
});
/**
 * マップデータからスクリーンのサイズを計算する
 */
exports.sceneScreenState = recoil_1.selector({
    key: 'sceneScreenState',
    get: function (_a) {
        var _b, _c;
        var get = _a.get;
        var tables = get(exports.sceneMapState).tables;
        var height = ((_b = tables[0]) === null || _b === void 0 ? void 0 : _b.length) || 0;
        var width = ((_c = tables[0]) === null || _c === void 0 ? void 0 : _c[0].length) || 0;
        return {
            height: height * next_1.size,
            width: width * next_1.size
        };
    }
});
exports.sceneState = recoil_1.selector({
    key: 'sceneState',
    get: function (_a) {
        var get = _a.get;
        var debug = get(exports.debugState);
        var map = get(exports.sceneMapState);
        var screen = get(exports.sceneScreenState);
        return { debug: debug, map: map, screen: screen };
    }
});
exports.undoPatchesState = recoil_1.atom({
    key: 'undoPatchesState',
    default: []
});
exports.editingState = recoil_1.selector({
    key: 'editingState',
    get: function (_a) {
        var get = _a.get;
        return {
            sceneMap: get(exports.sceneMapState),
            undoPatches: get(exports.undoPatchesState)
        };
    },
    set: function (_a, payload) {
        var set = _a.set, reset = _a.reset;
        if (payload instanceof recoil_1.DefaultValue) {
            reset(exports.sceneMapState);
            reset(exports.undoPatchesState);
        }
        else {
            set(exports.sceneMapState, payload.sceneMap);
            set(exports.undoPatchesState, payload.undoPatches);
        }
    }
});
exports.cursorState = recoil_1.atom({
    key: 'cursorState',
    default: null
});
var preloadSrcState = recoil_1.selectorFamily({
    key: 'preloadSrcState',
    get: function (src) { return function () { return fetch(src); }; }
});
exports.preloadNibState = recoil_1.selector({
    key: 'preloadNibState',
    get: function (_a) {
        var e_1, _b, e_2, _c;
        var get = _a.get;
        var nib = get(exports.paletteNibState);
        try {
            for (var nib_1 = __values(nib), nib_1_1 = nib_1.next(); !nib_1_1.done; nib_1_1 = nib_1.next()) {
                var row = nib_1_1.value;
                try {
                    for (var row_1 = (e_2 = void 0, __values(row)), row_1_1 = row_1.next(); !row_1_1.done; row_1_1 = row_1.next()) {
                        var tile = row_1_1.value;
                        get(preloadSrcState(tile.src));
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (row_1_1 && !row_1_1.done && (_c = row_1.return)) _c.call(row_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (nib_1_1 && !nib_1_1.done && (_b = nib_1.return)) _b.call(nib_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
});
/**
 * 【注意】
 * Scene['map']['base'] が表すタイルがパレット上のどこにあるかを表す
 * パレットとシーンの間でタイルの index を共通にすることを暗黙的な前提としている
 * しかし設計上そのような制約はないため、この Selection は疑わしい値とすべき
 * 例えば base の初期値はパレットに存在しない草原なので、本来表示することはできないが、
 * 便宜上、最も若い page の最も左上の座標を baseSelection として提供する
 */
exports.baseSelectionState = recoil_1.selector({
    key: 'baseSelectionState',
    get: function (_a) {
        var e_3, _b, e_4, _c;
        var get = _a.get;
        var pages = get(exports.palettePagesState);
        var base = get(exports.sceneMapState).base;
        try {
            for (var pages_1 = __values(pages), pages_1_1 = pages_1.next(); !pages_1_1.done; pages_1_1 = pages_1.next()) {
                var item = pages_1_1.value;
                try {
                    for (var _d = (e_4 = void 0, __values(Object.entries(item.tiles))), _e = _d.next(); !_e.done; _e = _d.next()) {
                        var _f = __read(_e.value, 2), number = _f[0], tile = _f[1];
                        if ((tile === null || tile === void 0 ? void 0 : tile.index) === base) {
                            // 同じ index が見つかった
                            var num = parseInt(number);
                            var col = num % 8;
                            var row = Math.floor(num / 8);
                            return {
                                page: item.index,
                                start: { col: col, row: row, num: num },
                                end: { col: col, row: row, num: num }
                            };
                        }
                    }
                }
                catch (e_4_1) { e_4 = { error: e_4_1 }; }
                finally {
                    try {
                        if (_e && !_e.done && (_c = _d.return)) _c.call(_d);
                    }
                    finally { if (e_4) throw e_4.error; }
                }
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (pages_1_1 && !pages_1_1.done && (_b = pages_1.return)) _b.call(pages_1);
            }
            finally { if (e_3) throw e_3.error; }
        }
        // 見つからないので最も若い page の最も左上の座標を返す
        return {
            page: pages[0].index,
            start: { col: 0, row: 0, num: 0 },
            end: { col: 0, row: 0, num: 0 }
        };
    },
    set: function (_a, newValue) {
        var get = _a.get, set = _a.set;
        var pages = get(exports.palettePagesState);
        if (newValue instanceof recoil_1.DefaultValue) {
            return; // リセットは定義できない（する必要もない）
        }
        var page = pages.find(function (item) { return item.index === newValue.page; });
        var tile = page === null || page === void 0 ? void 0 : page.tiles[String(newValue.start.num)];
        if (!tile)
            return;
        set(exports.editingState, function (curr) { return updateBase_1.updateBase(curr, tile); });
    }
});
//# sourceMappingURL=index.js.map