'use strict';

const fs = require('fs');
const path = require('path');

/** Unity spritePivot + 贴图尺寸（PPU=100）— 无主题数据时的回退 */
const TILE_META = {
    Baseblock: { width: 101, height: 80, pivotX: 0.5, pivotY: 0.92 },
    JumpBlock: { width: 101, height: 99, pivotX: 0.5, pivotY: 0.77 },
    WallBlock: { width: 101, height: 115, pivotX: 0.5, pivotY: 0.67 },
    kuai11: { width: 101, height: 74, pivotX: 0.5, pivotY: 1.01 },
};

let themeTileMeta = null;

function loadThemeTileMeta() {
    if (themeTileMeta) return themeTileMeta;
    try {
        const fp = path.join(Editor.Project.path, 'assets/resources/theme/tile-display-meta.json');
        if (fs.existsSync(fp)) {
            const data = JSON.parse(fs.readFileSync(fp, 'utf8'));
            themeTileMeta = data.themes || {};
            return themeTileMeta;
        }
    } catch (e) {
        console.warn('[tile-meta] 读取 tile-display-meta.json 失败', e);
    }
    themeTileMeta = {};
    return themeTileMeta;
}

function normalizeTheme(theme) {
    if (!theme) return undefined;
    if (theme === 'redArmy') return 'redarmy';
    return theme;
}

function getTileMeta(tileName, theme) {
    const key = normalizeTheme(theme);
    if (key) {
        const themes = loadThemeTileMeta();
        const entry = themes[key]?.[tileName];
        if (entry) {
            return {
                width: entry.width,
                height: entry.height,
                pivotX: entry.pivotX,
                pivotY: entry.pivotY,
            };
        }
    }
    return TILE_META[tileName] || TILE_META.Baseblock;
}

/**
 * 格子中心 + Unity spritePivot；宽度贴满菱形格，保留高度供等距遮挡。
 */
function spriteDrawRect(anchorX, anchorY, imgW, imgH, meta, halfW) {
    const hw = halfW || 50;
    const srcW = imgW || meta.width;
    const srcH = imgH || meta.height;
    const scale = (2 * hw) / srcW;
    const w = srcW * scale;
    const h = srcH * scale;
    return {
        x: anchorX - w * meta.pivotX,
        y: anchorY - (1 - meta.pivotY) * h,
        w,
        h,
    };
}

module.exports = { TILE_META, getTileMeta, spriteDrawRect, loadThemeTileMeta };
