#include "setup_wires.h"

static uint8_t wires_state = 0;

void print_wires(WireColor* wires, int editing_idx) {
    bool cut[NUM_WIRES];
    solve_wires(wires, cut);

    char string_buf[NUM_WIRES+1] = {0};
    wires_to_string(wires, string_buf);
    lcd_print(1, 1, string_buf);

    cut_to_string(cut, string_buf);
    lcd_print(2, 1, string_buf);

    wires_state = get_wires();
    for (int i = 0; i < NUM_WIRES; i++) {
        if (wires_state & (1<<i)) {
            string_buf[i] = ' ';
        } else {
            string_buf[i] = '!';
        }
    }
    lcd_print(3, 1, string_buf);

    lcd_set_cursor_vis(true);
    lcd_set_cursor_resting_position(1, editing_idx+1);
}

void setup_wires(void) {
    clear_all_pressed_released();
    get_cut_wires();
    lcd_clear();
    lcd_set_cursor_vis(true);

    WireColor wires[NUM_WIRES];
    load_wires_from_sd_card(wires);

    int editing_idx = 0;
    print_wires(wires, editing_idx);

    KeypadKey key;
    ButtonKey button;

    while (1) {
        while (get_keypad_pressed(&key)) {
            if (key == KeypadKey::k1) {
                generate_new_wires(wires);
                save_wires_to_sd_card(wires);
                print_wires(wires, editing_idx);
            } else if (key == KeypadKey::pound) {
                lcd_set_cursor_vis(false);
                return;
            }
        }

        while (get_button_pressed(&button)) {
            if (button == ButtonKey::b1) {
                // left
                editing_idx = editing_idx - 1;
                if (editing_idx < 0) editing_idx = 0;
            } else if (button == ButtonKey::b4) {
                // right
                editing_idx = editing_idx + 1;
                if (editing_idx >= NUM_WIRES) editing_idx = NUM_WIRES-1;
            } else if (button == ButtonKey::b2) {
                // down
                wires[editing_idx] = (WireColor)(((int)(wires[editing_idx]) + (NUM_COLORS-1)) % NUM_COLORS);
            } else if (button == ButtonKey::b3) {
                // up
                wires[editing_idx] = (WireColor)(((int)(wires[editing_idx]) + 1) % NUM_COLORS);
            }
            save_wires_to_sd_card(wires);
            print_wires(wires, editing_idx);
        }

        uint8_t new_wires_state = get_wires();
        if (new_wires_state != wires_state) {
            print_wires(wires, editing_idx);
        }
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}
