#include "device/device.h"
#include "game.h"
#include "sys/sys.h"

uint32_t game_frame;

int32_t ellipse_x0 = 32 * 4;
int32_t ellipse_y0 = 32 * 4;
int32_t ellipse_dx0 = 1;
int32_t ellipse_dy0 = 2;
int32_t ellipse_x1 = 96 * 4;
int32_t ellipse_y1 = 96 * 4;
int32_t ellipse_dx1 = 3;
int32_t ellipse_dy1 = 4;


const char* game_title() {
    return "Croc Party!";
}

void game_init() {
    sys_init();

    game_frame = 0;

    for (uint32_t x = 0; x < 8; x++) {
        for (uint32_t y = 0; y < 8; y++) {
            for (uint32_t z = 0; z < 4; z++) {
                sys_spal_set(
                    (x << 5)|(y << 2)|(z),

                    ((x * 255)/7) << 24 | 
                    ((y * 255)/7) << 16 | 
                    ((z * 255)/3) << 8
                );
            }
        }
    }
    sys_spal_set(0xfe, 0xffffffff);
}

void game_destroy() {
    sys_destroy();
}

void game_update() {
    game_frame += 4;

    ellipse_x0 += ellipse_dx0;
    if (ellipse_x0 < 0 || ellipse_x0 > DEVICE_W * 4) { ellipse_dx0 *= -1; }
    ellipse_y0 += ellipse_dy0;
    if (ellipse_y0 < 0 || ellipse_y0 > DEVICE_H * 4) { ellipse_dy0 *= -1; }

    ellipse_x1 += ellipse_dx1;
    if (ellipse_x1 < 0 || ellipse_x1 > DEVICE_W * 4) { ellipse_dx1 *= -1; }
    ellipse_y1 += ellipse_dy1;
    if (ellipse_y1 < 0 || ellipse_y1 > DEVICE_H * 4) { ellipse_dy1 *= -1; }
}

void game_draw() {
    sys_dpal_set(0xff, 0xfe);  // map to a non-transparent color

    for (int x = 0; x < DEVICE_W; x++) {
        for (int y = 0; y < DEVICE_H; y++) {
            uint32_t r = (x * 255)/(DEVICE_W - 1);
            uint32_t g = (y * 255)/(DEVICE_H - 1);
            uint32_t b = game_frame & 0x100 ? 0xff - game_frame & 0xff : game_frame & 0xff;
            if (x % 4 == 2 && y % 4 == 2) {
                r = 255 - r;
                g = 255 - g;
                b = 255 - b;
            }
            sys_color color = (r >> 5) << 5 | (g >> 5) << 2 | (b >> 6);
            sys_pixel_set(x, y, color);
        }
    }

    for (int i = 0; i < DEVICE_BUTTON_N; i++) {
        sys_pixel_set(i, 0, device_buttons[i] ? 0x00 : 0xff);
    }

    int x0 = ellipse_x0 / 4;
    int y0 = ellipse_y0 / 4;
    int x1 = ellipse_x1 / 4;
    int y1 = ellipse_y1 / 4;
    sys_oval_draw_ext(x0, y0, x1, y1, 10, true);
    sys_oval_draw_ext(x0, y0, x1, y1, 248, false);
    sys_circ_draw_ext(x0, y0, 4, 252, true);
    sys_circ_draw_ext(x0, y0, 6, 248, false);
    sys_circ_draw_ext(x0, y0, 8, 244, false);
    sys_line_draw(x0, y0, x1, y1, 254);

    sys_print("Hello, blood\nsources!", x1, y1, 224);
}
