/*
    * app.cpp
    * User management applet launcher and desktop integration entry points
    * Copyright (c) 2026 Daniel Hammer
*/

#include "usermanager_internal.hpp"

namespace usermanager_app {

static void usermanager_on_draw(Window* win, Framebuffer& fb) {
    (void)fb;
    UserManagerState* st = (UserManagerState*)win->app_data;
    if (!st) return;

    Canvas c(win);
    usermanager_draw(c, st);
}

static void usermanager_on_mouse(Window* win, MouseEvent& ev) {
    UserManagerState* st = (UserManagerState*)win->app_data;
    if (!st) return;

    mtk::DesktopHost host(win);
    int mx = 0;
    int my = 0;
    if (!host.map_mouse(ev, &mx, &my)) return;

    usermanager_update_mouse(st, mx, my);
    if (ev.left_pressed()) {
        usermanager_handle_click(win, st, mx, my);
    }
}

static void usermanager_on_key(Window* win, const Montauk::KeyEvent& key) {
    (void)win;
    (void)key;
}

static void usermanager_on_close(Window* win) {
    if (win->app_data) {
        montauk::mfree(win->app_data);
        win->app_data = nullptr;
    }
}

} // namespace usermanager_app

void open_user_manager(DesktopState* ds) {
    int idx = desktop_create_window(ds, "User Management", 200, 100, 480, 384);
    if (idx < 0) return;

    Window* win = &ds->windows[idx];
    usermanager_app::UserManagerState* st =
        (usermanager_app::UserManagerState*)montauk::malloc(sizeof(usermanager_app::UserManagerState));
    montauk::memset(st, 0, sizeof(usermanager_app::UserManagerState));
    st->desktop = ds;
    st->selected_user = -1;
    st->users_loaded = false;
    st->status_msg[0] = '\0';
    st->mouse_x = -1;
    st->mouse_y = -1;

    win->app_data = st;
    win->on_draw = usermanager_app::usermanager_on_draw;
    win->on_mouse = usermanager_app::usermanager_on_mouse;
    win->on_key = usermanager_app::usermanager_on_key;
    win->on_close = usermanager_app::usermanager_on_close;
}
