const std = @import("std");
const dvui = @import("dvui");
const WindowContext = @import("../WindowContext.zig");
const Document = @import("../models/Document.zig");
const json_io = @import("../persistence/json_io.zig");

pub fn menuBar(ctx: *WindowContext) void {
    var m = dvui.menu(@src(), .horizontal, .{ .background = true, .expand = .horizontal });
    defer m.deinit();

    if (dvui.menuItemLabel(@src(), "File", .{ .submenu = true }, .{ .expand = .none })) |r| {
        var fm = dvui.floatingMenu(@src(), .{ .from = r }, .{});
        defer fm.deinit();

        if (dvui.menuItemLabel(@src(), "Open", .{}, .{ .expand = .horizontal }) != null) {
            m.close();
            openDocumentDialog(ctx);
        }

        if (dvui.menuItemLabel(@src(), "Save As", .{}, .{ .expand = .horizontal }) != null) {
            m.close();
            saveAsDialog(ctx);
        }
    }
}

fn openDocumentDialog(ctx: *WindowContext) void {
    const path_z = dvui.dialogNativeFileOpen(ctx.allocator, .{
        .title = "Open",
        .filters = &.{ "*.json" },
        .filter_description = "JSON files",
    }) catch |err| {
        std.debug.print("Open dialog error: {}\n", .{err});
        return;
    } orelse return;
    defer ctx.allocator.free(path_z);

    const path = path_z[0..path_z.len];
    const doc = json_io.loadFromFile(Document, ctx.allocator, path) catch |err| {
        std.debug.print("Open file error: {}\n", .{err});
        return;
    };
    ctx.addDocument(doc) catch |err| {
        std.debug.print("Add document error: {}\n", .{err});
        return;
    };
}

fn saveAsDialog(ctx: *WindowContext) void {
    const open_doc = ctx.activeDocument() orelse return;
    const path_z = dvui.dialogNativeFileSave(ctx.allocator, .{
        .title = "Save As",
        .filters = &.{ "*.json" },
        .filter_description = "JSON files",
    }) catch |err| {
        std.debug.print("Save dialog error: {}\n", .{err});
        return;
    } orelse return;
    defer ctx.allocator.free(path_z);

    const path_raw = path_z[0..path_z.len];
    json_io.saveToFile(Document, &open_doc.document, path_raw) catch |err| {
        std.debug.print("Save file error: {}\n", .{err});
        return;
    };
}
