#include "input.h"
static bool check_pause_button(LandFloat mx, LandFloat my);
static bool check_title_button(LandFloat mx, LandFloat my);
static bool check_menu(LandFloat mx, LandFloat my, bool clicked);
void button_coordinates(int button, LandFloat * x, LandFloat * y, LandFloat * w, LandFloat * h) {
    float dw = land_display_width();
    float rr = dw / 32;
    float vd = rr * 1.25;
    if (button == 0) {
        * x = dw - rr;
        * y = 0;
        * w = rr;
        * h = rr;
    }
    if (button == 1) {
        * x = dw - rr;
        * y = vd;
        * w = rr;
        * h = rr;
    }
}
static bool check_pause_button(LandFloat mx, LandFloat my) {
    LandFloat x, y, w, h;
    button_coordinates(0, & x, & y, & w, & h);
    if (mx > x && my > y && mx < x + w && my < y + h) {
        return 1;
    }
    return 0;
}
static bool check_title_button(LandFloat mx, LandFloat my) {
    Application * a = app();
    if (! a->show_map) {
        return 0;
    }
    LandFloat x, y, w, h;
    button_coordinates(1, & x, & y, & w, & h);
    if (mx > x && my > y && mx < x + w && my < y + h) {
        return 1;
    }
    return 0;
}
static bool check_menu(LandFloat mx, LandFloat my, bool clicked) {
    if (! game->menu_on) {
        return 0;
    }
    return menu_tick(game->menu, mx, my, clicked);
}
void input_toggle_pause(void) {
    Application * a = app();
    if (a->editor) {
        menu_toggle();
    }
    else {
        if (a->show_map) {
            a->show_map = 0;
        }
        else {
            a->show_map = 1;
        }
    }
}
void input_tick(void) {
    Application * a = app();
    double mx = land_mouse_x();
    double my = land_mouse_y();
    bool holding = land_mouse_button(0);
    bool clicked = land_mouse_button_clicked(0);
    bool released = land_mouse_button_released(0);
    if (holding || released) {
        if (check_pause_button(mx, my)) {
            if (clicked) {
                input_toggle_pause();
            }
            return ;
        }
        if (check_title_button(mx, my)) {
            a->show_map = 0;
            main_switch_to_title(0);
            return ;
        }
        if (check_menu(mx, my, released)) {
            ;
        }
        else if (a->overview) {
            overview_click(game->overview, mx, my, clicked, released);
        }
        else if (a->editor) {
            editor_click(mx, my, clicked, released);
        }
        else if (clicked) {
            mx /= game->viewport->zoom;
            my /= game->viewport->zoom;
            unproject(game->viewport, mx, my, 0, & game->target_x, & game->target_z);
        }
    }
}
