import type { Component } from "../types/component";
import type {Screen} from "../types/screen";
import type {Table} from "../types/table";
import type { Project } from "../types/project";
import type { WidgetJson, TableJson, OutputJson } from "./jsonTypes";

const byIndex = <T extends { index: number }>(a: T, b: T) => a.index - b.index;

// name をキーにしたオブジェクトに変換(重複していたら例外)
const toRecord = <T, V>(
    items: T[],
    getKey: (item: T) => string,
    getValue: (item: T) => V,
    label: string,
): Record<string, V> => {
    const result: Record<string, V> = {};
    for (const item of items) {
    const key = getKey(item);
    if (key in result) throw new Error(`${label} の名前が重複しています: ${key}`);
    result[key] = getValue(item);
    }
    return result;
};

const toWidgetJson = (c: Component): WidgetJson => {
    const base = {
        wType: c.type, 
        wX: Math.round(c.uiData.posX),
        wY: Math.round(c.uiData.posY),
        wWidth: Math.round(c.uiData.width),
        wHeight: Math.round(c.uiData.height),
        wEnabled: c.uiData.enable,
        wVisible: c.uiData.visible
    };
    switch(c.type) {
        case "button": return {...base, wText: c.generalData.text};
        case "text": return {...base, wText: c.generalData.text};
        case "textField": return {...base, wText: c.generalData.text};
        case "table": return {...base};
    }
};

const toScreenJson = (s: Screen) =>
    toRecord(
    [...s.components].sort(byIndex),
    (c) => c.name,
    toWidgetJson,
    `画面「${s.name}」のコンポーネント`,
    );

const toTableJson = (t: Table): TableJson => {
    const keyColumn = t.columns.find((col) => col.isPrimary);
    if (!keyColumn) {
        throw new Error(`テーブル[${t.name}]に主キーがありません`)
    }
    return {
        keyName: keyColumn.name,
        columnName: t.columns.map((col) => col.name)
    };
};

export const toOutputJson = (p: Project): OutputJson => ({
    screen: toRecord([...p.screens].sort(byIndex), (s) => s.name, toScreenJson, "画面"),
    table: toRecord(p.tables, (t) => t.name, toTableJson, "テーブル"),
});