#include "eduwin.h"

/* 
 * JSON 示例：读取 data.json → 修改数据 → 保存回 data.json
 * 完整演示 json_parse / json_get_* / json_create_* / json_add_* / json_to_str
 */

static HWND g_info, g_status;

/* 加载 → 解析 → 显示 */
static void on_load(void *data)
{
    (void)data;

    WCHAR buf[4096];
    if (read_text_file(L"data.json", buf, 4096) < 0)
    {
        set_text(g_info, L"读取 data.json 失败");
        set_text(g_status, L"[错误] 文件不存在");
        return;
    }

    char *utf8 = wtou8(buf);
    if (!utf8) { set_text(g_info, L"编码转换失败"); return; }

    json_t *root = json_parse(utf8);
    free(utf8);
    if (!root) { set_text(g_info, L"JSON 解析失败"); return; }

    /* 用 json_to_str 显示原始内容 */
    char *raw = json_to_str(root);
    WCHAR *wraw = u8tow(raw ? raw : "{}");
    free(raw);

    if (wraw)
    {
        set_text(g_info, wraw);
        free(wraw);
    }

    /* 读取各字段，在状态栏显示 */
    const char *name = json_get_str(root, "name");
    int age   = json_get_int(root, "age");
    double sc = json_get_double(root, "score");

    WCHAR line[128];
    if (name)
    {
        WCHAR *wn = u8tow(name);
        str_format(line, 128, L"name=%s  age=%d  score=%.1f", wn ? wn : L"?", age, sc);
        free(wn);
    }
    else
    {
        str_format(line, 128, L"age=%d  score=%.1f", age, sc);
    }
    set_text(g_status, line);

    json_free(root);
}

/* 构建新 JSON → 保存回 data.json */
static void on_save(void *data)
{
    (void)data;

    json_t *root = json_create_obj();
    json_add_str(root, "name", "李四");
    json_add_int(root, "age", 20);
    json_add_double(root, "score", 88.5);

    /* 字符串数组 */
    json_t *skills = json_create_arr();
    json_arr_add(skills, json_create_str("C"));
    json_arr_add(skills, json_create_str("Python"));
    json_arr_add(skills, json_create_str("JSON"));
    json_add_arr(root, "skills", skills);

    char *out = json_to_str(root);
    json_free(root);

    WCHAR *wout = u8tow(out);
    free(out);
    if (!wout) { set_text(g_status, L"[错误] 编码失败"); return; }

    if (write_text_file(L"data.json", wout))
        set_text(g_status, L"已保存！点「加载」查看");
    else
        set_text(g_status, L"[错误] 写入失败");
    free(wout);
}

int main(void)
{
    if (init_app() != 0) return 1;

    HWND win = create_window(L"JSON 示例", 440, 280);
    if (!win) return 1;

    /* 显示 JSON 内容（多行，用文本框便于查看） */
    g_info   = create_text(win, L"点「加载」读取 data.json", 20, 20, 400, 150);
    set_readonly(g_info, 1);
    g_status = create_label(win, L"就绪", 20, 180, 400, 20);

    HWND btn_load = create_button(win, L"加载 JSON", 20,   210, 110, 28);
    HWND btn_save = create_button(win, L"修改并保存", 155, 210, 110, 28);

    on_button_click(btn_load, on_load, NULL);
    on_button_click(btn_save, on_save, NULL);

    show_window(win);
    run_app();
    return 0;
}
