#include "title.h"
#define _scramble_max(x, y) ((y) > (x) ? (y) : (x))
static str menu_text = "\n"
    "Play\n"
    "New Game\n"
    "    -Are you sure?\n"
    "    Delete savegame!\n"
    "    Continue Playing\n"
    "    Reset Current Level\n"
    "Settings\n"
    "    Controls\n"
    "        Left/Right\n"
    "            -Configure H axis\n"
    "            Left\n"
    "            Right\n"
    "            Done\n"
    "        Up/Down\n"
    "            -Configure V axis\n"
    "            Up\n"
    "            Down\n"
    "            Done\n"
    "        Jump/Pull\n"
    "            -Configure buttons\n"
    "            Jump/Pull\n"
    "            Menu\n"
    "            Done\n"
    "        Back\n"
    "    Audio\n"
    "        -Volume\n"
    "        Music\n"
    "        Sound\n"
    "        Back\n"
    "    Video\n"
    "        Fullscreen|Back to Windowed\n"
    "        Back\n"
    "    Back\n"
    "";
static MenuScreen * menu;
static MenuScreen * menu_main;
static int moment;
static bool selected_blocking;
bool finding_input;
int finding_control;
static int finding_progress;
static float ppx, ppy, ppw, pph;
static void _find_control(int c);
static int _indentation(str x);
static void drawvol(int v, float x, float y);
static int volget(float mx);
static void music_volume(int i);
static void sound_volume(int i);
static void draw_title_animation(void);
MenuScreen* menu_screen_new(void) {
    MenuScreen * self;
    land_alloc(self);
    self->items = land_array_new();
    return self;
}
MenuScreenItem* menu_screen_add(MenuScreen * self, str text) {
    Application * a = app();
    land_font_set(a->big);
    float w = land_display_width();
    float h = land_display_height();
    double s = 960 / w;
    w *= s;
    h *= s;
    if (land_equals(text, "Edit")) {
        if (! global_can_enable_editor) {
            return NULL;
        }
    }
    MenuScreenItem * item;
    land_alloc(item);
    if (land_starts_with(text, "-")) {
        item->disabled = 1;
        text++;
    }
    if (land_contains(text, "|")) {
        item->alternates = land_split(text, "|");
        text = land_array_get_nth(item->alternates, 0);
    }
    if (land_equals(text, "Controls")) {
        if (global_use_touch_input) {
            text = "Touch";
        }
    }
    item->text = text;
    item->w = land_text_get_width(text);
    item->h = land_line_height();
    land_array_add(self->items, item);
    self->w = 0;
    self->h = 0;
    int pos = 0;
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(self->items);
        for (MenuScreenItem * i = LandArrayIterator_item(self->items, &__iter0__); LandArrayIterator_next(self->items, &__iter0__); i = LandArrayIterator_item(self->items, &__iter0__)) {
            self->w = _scramble_max(self->w, i->w);
            self->h += i->h;
            i->pos = pos++;
        }
    }
    self->x = (w - self->w) / 2;
    self->y = (h - self->h) / 2;
    int i = 0;
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(self->items);
        for (MenuScreenItem * msi = LandArrayIterator_item(self->items, &__iter0__); LandArrayIterator_next(self->items, &__iter0__); msi = LandArrayIterator_item(self->items, &__iter0__)) {
            msi->x = (w - msi->w) / 2;
            msi->y = self->y + i * msi->h;
            i++;
        }
    }
    return item;
}
MenuScreenItem* menu_item_at(int x, int y) {
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(menu->items);
        for (MenuScreenItem * msi = LandArrayIterator_item(menu->items, &__iter0__); LandArrayIterator_next(menu->items, &__iter0__); msi = LandArrayIterator_item(menu->items, &__iter0__)) {
            if (x >= msi->x && y >= msi->y && y <= msi->y + msi->h) {
                // can click to the right
                return msi;
            }
        }
    }
    return NULL;
}
bool menu_is(str x) {
    return land_equals(menu->name, x);
}
MenuScreenItem* menu_item_get(void) {
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(menu->items);
        for (MenuScreenItem * msi = LandArrayIterator_item(menu->items, &__iter0__); LandArrayIterator_next(menu->items, &__iter0__); msi = LandArrayIterator_item(menu->items, &__iter0__)) {
            if (msi->selected) {
                return msi;
            }
        }
    }
    return NULL;
}
bool menu_item_is(str x) {
    MenuScreenItem * item = menu_item_get();
    if (! item) {
        return 0;
    }
    return land_equals(item->text, x);
}
void menu_screen_back(void) {
    if (menu_is("New Game")) {
        main_switch_to_game();
    }
    else if (menu_is("Controls")) {
        menu_goto("Settings");
    }
    else if (menu_is("Main")) {
        main_switch_to_game();
    }
    else {
        menu_goto("Main");
        save_info();
    }
}
void menu_goto(str x) {
    if (land_equals(x, "Main")) {
        menu = menu_main;
        return ;
    }
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(menu_main->items);
        for (MenuScreenItem * item = LandArrayIterator_item(menu_main->items, &__iter0__); LandArrayIterator_next(menu_main->items, &__iter0__); item = LandArrayIterator_item(menu_main->items, &__iter0__)) {
            if (land_equals(item->text, x)) {
                menu = item->target;
                return ;
            }
        }
    }
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(menu->items);
        for (MenuScreenItem * item = LandArrayIterator_item(menu->items, &__iter0__); LandArrayIterator_next(menu->items, &__iter0__); item = LandArrayIterator_item(menu->items, &__iter0__)) {
            if (land_equals(item->text, x)) {
                menu = item->target;
                return ;
            }
        }
    }
    print("Cannot goto menu %s", x);
}
void menu_goup(void) {
    menu = menu->parent;
}
void menu_select_next(int d) {
    int n = land_array_count(menu->items);
    bool sel = 0;
    for (int i = 0; i < n; i += 1) {
        MenuScreenItem * msi = land_array_get_or_none(menu->items, i);
        MenuScreenItem * prev = land_array_get_or_none(menu->items, i - d);
        if (msi->disabled) {
            continue;
        }
        if (msi->selected) {
            sel = 1;
        }
        if (prev && prev->selected) {
            prev->selected = 0;
            msi->selected = 1;
            return ;
        }
    }
    if (sel) {
        return ;
    }
    for (int i = 0; i < n; i += 1) {
        MenuScreenItem * msi = land_array_get_or_none(menu->items, i);
        if (msi->disabled) {
            continue;
        }
        msi->selected = 1;
        return ;
    }
}
void menu_sideways(int d) {
    Application * a = app();
    if (menu_is("Audio")) {
        if (menu_item_is("Music")) {
            music_volume(a->music + d);
        }
        if (menu_item_is("Sound")) {
            sound_volume(a->sound + d);
        }
    }
}
static void _find_control(int c) {
    finding_input = 1;
    finding_control = c;
    finding_progress = 0;
}
void menu_click(float x) {
    Application * a = app();
    MenuScreenItem * item = menu_item_get();
    if (item) {
        if (item->target) {
            if (menu_is("Main")) {
                if (menu_item_is("New Game")) {
                    a->code = 0;
                    a->godmode = 0;
                }
            }
            menu = item->target;
            return ;
        }
    }
    if (menu_is("Left/Right")) {
        if (menu_item_is("Left")) {
            _find_control(ControlLeft);
        }
        if (menu_item_is("Right")) {
            _find_control(ControlRight);
        }
        if (menu_item_is("Done")) {
            menu_goup();
        }
    }
    else if (menu_is("Up/Down")) {
        if (menu_item_is("Up")) {
            _find_control(ControlUp);
        }
        if (menu_item_is("Down")) {
            _find_control(ControlDown);
        }
        if (menu_item_is("Done")) {
            menu_goup();
        }
    }
    else if (menu_is("Jump/Pull")) {
        if (menu_item_is("Jump/Pull")) {
            _find_control(ControlJump);
        }
        if (menu_item_is("Menu")) {
            _find_control(ControlMenu);
        }
        if (menu_item_is("Done")) {
            menu_goup();
        }
    }
    else if (menu_is("Settings")) {
        if (menu_item_is("Touch")) {
            a->dpad++;
            if (a->dpad == 6) {
                a->dpad = 0;
            }
        }
    }
    else if (menu_is("Audio")) {
        if (menu_item_is("Music")) {
            music_volume(volget(x));
        }
        else if (menu_item_is("Sound")) {
            sound_volume(volget(x));
        }
    }
    else if (menu_is("Video")) {
        if (menu_item_is("Fullscreen")) {
            #ifdef ANDROID
            a->fullscreen = ! a->fullscreen;
            make_frameless(a->fullscreen);
            #else
            land_display_toggle_fullscreen();
            a->fullscreen = (land_display_flags() & LAND_FULLSCREEN) != 0;
            #endif
            item->choice = a->fullscreen ? 1 : 0;
        }
    }
    else if (menu_is("New Game")) {
        if (menu_item_is("Delete savegame!")) {
            // start new game
            save_new();
            a->editor = 0;
            main_switch_to_game();
        }
        else if (menu_item_is("Continue Playing")) {
            a->editor = 0;
            main_switch_to_game();
        }
        else if (menu_item_is("Reset Current Level")) {
            a->editor = 0;
            save_reset_room(game->level);
            main_switch_to_game();
        }
    }
    else if (menu_is("Controls")) {
        ;
    }
    else if (menu_is("Main")) {
        if (menu_item_is("Play")) {
            a->editor = 0;
            // load saved game
            main_switch_to_game();
        }
        else if (menu_item_is("Reset Room")) {
            // reset the current room
            save_reset_room(game->level);
            main_switch_to_game();
        }
    }
    //if game.skunk:
    //    player_find_entrance(game.skunk)
    if (menu_item_is("Back")) {
        menu_screen_back();
    }
}
static int _indentation(str x) {
    int i = 0;
    while (x [i] == ' ') {
        i++;
    }
    return i;
}
void title_init(void) {
    MenuScreen * menus [100];
    menus [0] = menu_main = menu_screen_new();
    menu_main->name = "Main";
    LandArray * rows = land_split_lines(menu_text);
    int prev_nested = 0;
    MenuScreenItem * prev_item = NULL;
    MenuScreen * prev_menu = NULL;
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(rows);
        for (str row_raw = LandArrayIterator_item(rows, &__iter0__); LandArrayIterator_next(rows, &__iter0__); row_raw = LandArrayIterator_item(rows, &__iter0__)) {
            int nested = _indentation(row_raw);
            if (nested > prev_nested) {
                menus [nested] = menu_screen_new();
                menus [nested]->name = prev_item->text;
                if (! land_equals(prev_item->text, "Touch")) {
                    prev_item->target = menus [nested];
                }
                menus [nested]->parent = prev_menu;
            }
            prev_nested = nested;
            prev_menu = menus [nested];
            char * row = land_strdup(row_raw);
            land_strip(& row);
            if (! row [0]) {
                continue;
            }
            prev_item = menu_screen_add(menus [nested], row);
        }
    }
    land_array_destroy_with_strings(rows);
    menu = menu_main;
    menu_select_next(1);
}
// 0 = main, 1 = settings
void title_com(int com) {
    if (com == 1) {
        menu_goto("Settings");
    }
    else {
        menu_goto("Main");
    }
}
void title_tick(void) {
    Application * a = app();
    float w = land_display_width();
    double s = 960 / w;
    if (land_key_pressed(LandKeyEscape)) {
        if (menu_is("Main")) {
            save_level(0, 0);
            land_quit();
        }
        else {
            menu_screen_back();
        }
    }
    if (land_key_pressed('e')) {
        if (global_can_enable_editor) {
            a->editor = 1;
            main_switch_to_game();
        }
    }
    if (land_key_pressed(LandKeyBack) || controls.pressed [ControlMenu]) {
        menu_screen_back();
    }
    if (selected_blocking) {
        if (! a->up && ! a->down && ! a->left && ! a->right) {
            selected_blocking = 0;
        }
    }
    else if (a->up || a->down) {
        menu_select_next(a->up ? - 1 : 1);
        selected_blocking = 1;
    }
    else if (a->left || a->right) {
        menu_sideways(a->left ? - 1 : 1);
        selected_blocking = 1;
    }
    bool click = 0;
    float x = 0, y = 0;
    MenuScreenItem * msi = NULL;
    MenuScreenItem * prev = menu_item_get();
    x = land_mouse_x() * s;
    y = land_mouse_y() * s;
    if (land_mouse_button_clicked(0)) {
        click = 1;
        msi = menu_item_at(x, y);
    }
    if (controls.pressed [ControlJump]) {
        click = 1;
        msi = menu_item_get();
    }
    if (click) {
        if (msi) {
            if (prev) {
                prev->selected = 0;
            }
            msi->selected = 1;
        }
        print("%f %f %f %f %f %f", x, y, ppx, ppy, ppw, pph);
        if (x > ppx && x < ppx + ppw && y > ppy && y < ppy + pph) {
            open_link("https://tins.amarillion.org");
            return ;
        }
    }
    if (click && msi) {
        if (menu_is("New Game") && msi->pos == 0) {
            a->code++;
            if (a->code == 7) {
                sound(Data_glass, 1);
                a->godmode = 1;
            }
        }
        else {
            menu_click(x - (msi->x + msi->w));
        }
    }
}
static void drawvol(int v, float x, float y) {
    LandColor c = land_color_get();
    y += 16;
    float s = 48;
    for (int i = 0; i < 7; i += 1) {
        float ix = x + i * s;
        float iy = y;
        land_color(1, 0, 0.5, 1);
        if (i <= v) {
            if (v == 0) {
                land_color(0, 0, 0, 1);
            }
            land_filled_rectangle(ix, iy, ix + s * 0.8, iy + s);
        }
        else {
            float cx = ix + s * 0.4;
            float cy = iy + s * 0.5;
            land_filled_circle(cx - 4, cy - 4, cx + 4, cy + 4);
        }
    }
    land_color_set(c);
}
void menu_screen_draw(void) {
    Application * a = app();
    land_font_set(a->big);
    land_color(.9, .9, 0.7, 1);
    {
        LandArrayIterator __iter0__ = LandArrayIterator_first(menu->items);
        for (MenuScreenItem * item = LandArrayIterator_item(menu->items, &__iter0__); LandArrayIterator_next(menu->items, &__iter0__); item = LandArrayIterator_item(menu->items, &__iter0__)) {
            float y = item->y;
            float x = item->x;
            bool draw = 1;
            land_text_pos(x, y);
            land_color(0.5, 0, 0, 1);
            if (item->selected) {
                land_color(0.9, 0.1, 0, 1);
                if (finding_input) {
                    if ((land_get_ticks() / 5) % 2 == 0) {
                        land_color(1, 1, 1, 1);
                    }
                }
            }
            else {
                land_color(0.5, 0, 0, 1);
            }
            if (menu_is("Settings")) {
                if (item->pos == 0) {
                    if (global_use_touch_input) {
                        if (a->dpad == 0) {
                            land_print("DPad left");
                        }
                        if (a->dpad == 1) {
                            land_print("DPad right");
                        }
                        if (a->dpad == 2) {
                            land_print("DPad left big");
                        }
                        if (a->dpad == 3) {
                            land_print("DPad right big");
                        }
                        if (a->dpad == 4) {
                            land_print("double click swipe");
                        }
                        if (a->dpad == 5) {
                            land_print("two finger swipe");
                        }
                        draw = 0;
                    }
                }
            }
            else if (menu_is("Audio")) {
                if (item->pos == 1) {
                    drawvol(a->music, x + item->w, y);
                }
                else if (item->pos == 2) {
                    drawvol(a->sound, x + item->w, y);
                }
            }
            else if (menu_is("New Game")) {
                if (item->pos == 0) {
                    land_color(1, 0.75, 0.75, 1);
                }
                else if (item->pos == 2) {
                    if (item->selected) {
                        land_color(1, 0.4, 0.4, 1);
                    }
                }
                else if (item->pos == 3) {
                    if (item->selected) {
                        land_color(0, 0.5, 0, 1);
                    }
                }
            }
            if (draw) {
                if (item->alternates) {
                    land_print(land_array_get_nth(item->alternates, item->choice));
                }
                else {
                    land_print(item->text);
                }
            }
            int control = ControlNone;
            if (menu_is("Left/Right")) {
                if (item->pos == 1) {
                    control = ControlLeft;
                }
                if (item->pos == 2) {
                    control = ControlRight;
                }
            }
            if (menu_is("Up/Down")) {
                if (item->pos == 1) {
                    control = ControlUp;
                }
                if (item->pos == 2) {
                    control = ControlDown;
                }
            }
            if (menu_is("Jump/Pull")) {
                if (item->pos == 1) {
                    control = ControlJump;
                }
                if (item->pos == 2) {
                    control = ControlMenu;
                }
            }
            if (menu_is("Controls")) {
                if (item->pos == 1) {
                    control = ControlLeft;
                }
                if (item->pos == 2) {
                    control = ControlUp;
                }
                if (item->pos == 3) {
                    control = ControlJump;
                }
            }
            if (control) {
                land_font_set(a->medium);
                land_text_pos(item->x + item->w, y);
                land_color(0, 0, 0, 0.33);
                land_print(control_name(control));
                land_font_set(a->big);
            }
        }
    }
}
static int volget(float mx) {
    float sx = 48;
    int i = mx / sx;
    return i;
}
static void music_volume(int i) {
    Application * a = app();
    if (i < 0) {
        i = 0;
    }
    if (i > 6) {
        i = 6;
    }
    a->music = i;
    song_volume();
}
static void sound_volume(int i) {
    Application * a = app();
    if (i < 0) {
        i = 0;
    }
    if (i > 6) {
        i = 6;
    }
    a->sound = i;
    sound(Data_on, 1);
}
float align(float x, float s) {
    return floor(x * s) / s;
}
void title_render(void) {
    Application * a = app();
    float w = land_display_width();
    float h = land_display_height();
    double s = w / 960;
    h /= s;
    land_clear(1, 1, 1, 0);
    land_reset_transform();
    land_scale(s, s);
    land_font_set(a->big);
    if (menu_is("Settings")) {
        land_font_set(a->medium);
        land_color(0.5, 0, 0, 1);
        float nh = land_line_height();
        float y = (h - menu->h) / 2;
        float x = (w - menu->w) / 2;
        land_text_pos(x, y - nh * 2);
        if (global_use_touch_input) {
            if (a->dpad == 5) {
                land_print("Jump: touch second finger");
                land_print("Pull/Lift: two finger swipe");
            }
            else if (a->dpad == 4) {
                land_print("Jump: Move then double tap");
                land_print("Pull/Lift: Double tap then move");
            }
            else {
                land_print("Jump: Hold move then jump");
                land_print("Pull/Lift: Hold jump then move");
            }
        }
        else {
            land_print("Jump: Press button while moving");
            land_print("Pull/Lift: Press button first then move");
        }
        land_font_set(a->big);
    }
    if (1) {
        float y = 0;
        float x = 960 / 2;
        land_color_set(land_color_name("orchid"));
        land_text_pos(x, y);
        land_print_center(TITLE);
        land_font_set(a->medium);
        land_print_center("A fable written by AI");
    }
    menu_screen_draw();
    land_font_set(a->font);
    land_color(0, 0, 0, 1);
    moment++;
    if (moment > 4) {
        // wait a moment so Android gets a moment to recover and
        // won't crash :P
        draw_title_animation();
    }
    a->tint.a = 0;
    land_font_set(a->font);
    land_text_pos(960 - 8, h - land_line_height() * 3);
    int t = a->time / 60;
    int f = 0;
    for (int i = 0; i < 8; i += 1) {
        if (game->flower [i]) {
            f++;
        }
    }
    int tt = 0;
    for (int i = 0; i < 8; i += 1) {
        if (game->test_tube [i]) {
            tt++;
        }
    }
    //land_print_right("Flowers picked: %d/7", f)
    //land_print_right("Test tubes: %d/7", tt)
    //land_print_right("Car keys found: %s", game->key ? "yes" : "no")
    land_print_right("Died %d time%s.", game->deaths, game->deaths != 1 ? "s" : "");
    land_print_right("Playtime on this savegame: %02d:%02d:%02d", t / 3600, (t / 60) % 60, t % 60);
    land_print_right("Version %s", VERSION);
    land_font_set(a->medium);
    land_color(.3, 0.3, 1, 1);
    land_text_pos(20, h - 4 - land_line_height());
    land_print("tins.amarillion.org");
    ppx = land_text_x();
    ppy = land_text_y();
    ppw = land_text_width();
    pph = land_text_height();
}
static void draw_title_animation(void) {
    ;
}
