#include <stdio.h>
#include "gpio.h"
#include "ui.h"
#include "keypad.h"
#include "global.h"
#include "time.h"
#include "kt0915.h"

/** test */
#include "ui_menu.h"
#include "ui_utils.h"

static const uint8_t *item_text = u8str("qwertyuiop");
static StrItem app_get_item(uint16_t index) {
    if (index >= 10) {
        return NULL_STR_ITEM;
    }
    StrItem item = { item_text, 1 };
    item.text += index;
    return item;
}

void test() {
    ST7735_FillScreen(ST7735_BLACK);
    printf("test start.\n");
    while (1) {
        IndexResult res = iui_list_select(u8str("Kobold's Menu"), 33, app_get_item, 0);
        printf("You Selected '%s'\n", app_get_item(res.index).text);
        if (res.confirmed) {
            printf("and you confirmed it.\n");
        } else {
            printf("but you canceled it.\n");
        }
    }
    // end
    printf("test end.\n");
    while (1) {
    }
}
/** test end */

void __limit_freq_range() {
    uint16_t limit_min = (global_data.rf_mode == G_RF_MODE_AM) ? G_AM_FREQ_MIN : G_FM_FREQ_MIN;
    uint16_t limit_max = (global_data.rf_mode == G_RF_MODE_AM) ? G_AM_FREQ_MAX : G_FM_FREQ_MAX;
    if (global_data.freq < limit_min) {
        global_data.freq = limit_min;
    } else if (global_data.freq > limit_max) {
        global_data.freq = limit_max;
    }
}

void __ensure_mute() {
    if (global_data.flag & G_FL_MUTE) {
        KT0915_setAudioMute(1);
    } else {
        KT0915_setAudioMute(0);
    }
}

void __send_freq() {
    if (global_data.rf_mode == G_RF_MODE_AM) {
        KT0915_setFrequency(global_data.freq);
        printf("Set Frequency to %u kHz\n", global_data.freq);
    } else {
        KT0915_setFrequency(global_data.freq * 50ul);
        printf("Set Frequency to %lu kHz\n", global_data.freq * 50ul);
    }
}

void __send_volumn() {
    KT0915_setVolume(global_data.volumn);
    printf("Set Volumn to %u\n", global_data.volumn);
}

void __switch_to_fm() {
    KT0915_setFM(G_FM_FREQ_MIN * 50ul, G_FM_FREQ_MAX * 50ul, G_FM_FREQ_MIN * 50ul, 50u);
    printf("Switched to FM Mode\n");
    __send_freq();
    __ensure_mute();
}

void __switch_to_am() {
    KT0915_setAM(G_AM_FREQ_MIN, G_AM_FREQ_MAX, G_AM_FREQ_MIN, 1, 0);
    printf("Switched to AM Mode\n");
    __send_freq();
    __ensure_mute();
}

uint16_t __read_rssi() {
    if (global_data.rf_mode == G_RF_MODE_AM) {
        return (uint16_t)KT0915_getAmRssi() / 3;
    } else {
        return (uint16_t)KT0915_getFmRssi() / 3;
    }
}

void __init_kt0915() {
    KT0915_enable(1);
    KT0915_setup(OSCILLATOR_32KHZ, 0);
    KT0915_setSoftMute(1);
    KT0915_setMono(0);
    uint16_t did = KT0915_getDeviceId();
    printf("kt0915 device id: %X\n", did);
    __switch_to_fm();
    __send_volumn();
    KT0915_setSoftMute(0);
}

static int32_t target_time_stamp = 0;
void timer_event() {
    if (ticks_diff(ticks_ms(), target_time_stamp) > 0) {
        target_time_stamp = ticks_add(target_time_stamp, 500);
        // update rssi
        global_data.signal = __read_rssi();
        ui_com_sig_bar(0);
    }
}

void app_init() {
    // 程序开始时执行一次
    printf("\n====start====\n");
    target_time_stamp = ticks_add(ticks_ms(), 500);
    kp_query();
    // __init_kt0915();
    // ui_screen_main();
    test();
}

void app_main_loop() {
    // 反复被调用执行
    uint8_t event = kp_query();
    uint8_t event_type = kp_Type(event);
    uint8_t event_value = kp_Value(event);
    if (event_type == kp_ROTATE_RIGHT || event_type == kp_ROTATE_LEFT) {
        if (global_data.point_mode & G_PMOD_MODE_MASK) {
            // 指针模式调整
            uint8_t p_pos = bit_fetch(global_data.point_mode, G_POMD_POS_BOFF, G_POMD_POS_MASK);
            if (global_data.point_mode & G_PMOD_PMOVE_MASK) {
                // 调整指针位置
                if (event_type == kp_ROTATE_RIGHT) {
                    p_pos += 100;
                    p_pos -= event_value;
                } else {
                    p_pos += event_value;
                }
                p_pos %= 5; // 0~4, 右边第一个数值为0号位置
                bit_replace(global_data.point_mode, p_pos, G_POMD_POS_BOFF, G_POMD_POS_MASK);
                printf("Adjust Point Pos: %u\n", p_pos);
            } else {
                // 调整指针位置的数字
                uint16_t num_freq;
                if (global_data.rf_mode == G_RF_MODE_AM) {
                    num_freq = global_data.freq;
                } else {
                    num_freq = global_data.freq * 5;
                }
                /* adjust number at all */
                uint16_t scale = 1;
                if (p_pos == 0 && global_data.rf_mode == G_RF_MODE_FM) {
                    scale = 5;
                } else {
                    uint8_t tmp;
                    for (tmp = 0; tmp < p_pos; tmp ++) {
                        scale *= 10;
                    }
                }
                if (event_type == kp_ROTATE_RIGHT) {
                    num_freq += scale * event_value;
                } else {
                    if (scale * event_value < num_freq) {
                        num_freq -= scale * event_value;
                    } else {
                        num_freq = 0;
                    }
                }
                uint16_t limit_min = (global_data.rf_mode == G_RF_MODE_AM) ? G_AM_FREQ_MIN : G_FM_FREQ_MIN * 5;
                uint16_t limit_max = (global_data.rf_mode == G_RF_MODE_AM) ? G_AM_FREQ_MAX : G_FM_FREQ_MAX * 5;
                if (num_freq > limit_max || num_freq < limit_min) {
                    return; // ignore if overflow
                }
                /* adjust number one by one */
                // uint8_t scale = 1;
                // uint16_t tmp;
                // uint16_t num_lower, num_upper;
                // uint8_t inc = (p_pos == 0 && global_data.rf_mode == G_RF_MODE_FM) ? 5 : 1;
                // uint8_t lim = 10;
                // if (p_pos == 4) {
                //     if (global_data.rf_mode == G_RF_MODE_AM) {
                //         lim = 3;
                //     } else {
                //         lim = 1;
                //     }
                // }
                // for (tmp = 0; tmp < p_pos; tmp ++) {
                //     scale *= 10;
                // }
                // num_lower = num_freq % scale;
                // num_upper = num_freq / scale / 10;
                // tmp = num_freq / scale % 10;
                // if (event_type == kp_ROTATE_RIGHT) {
                //     tmp += (event_value * inc);
                // } else {
                //     tmp += lim % 100;
                //     tmp -= (event_value * inc);
                // }
                // tmp %= lim;
                // num_freq = (num_upper * scale * 10) + (tmp * scale) + num_lower;
                if (global_data.rf_mode == G_RF_MODE_AM) {
                    global_data.freq = num_freq;
                } else {
                    global_data.freq = num_freq / 5;
                }
                printf("Adjust Freq: %u\n", global_data.freq);
                __limit_freq_range();
                __send_freq();
            }
        } else {
            // 直接调整频率
            if (global_data.rf_mode == G_RF_MODE_FM) {
                event_value = event_value * 2;
            }
            if (event_type == kp_ROTATE_RIGHT) {
                global_data.freq += event_value;
            } else {
                global_data.freq -= event_value;
            }
            printf("Adjust Freq: %u\n", global_data.freq);
            __limit_freq_range();
            __send_freq();
        }
        ui_com_freq_digital(1, 0);
    } else if (event_type == kp_SHORT_CLICK) {
        if (global_data.point_mode & G_PMOD_MODE_MASK) {
            if (event_value == kp_KEYENCODER) {
                if (global_data.point_mode & G_PMOD_PMOVE_MASK) {
                    // 退出移动指针模式
                    bit_clear(global_data.point_mode, G_PMOD_PMOVE_MASK);
                    printf("Exit Pointer Move Mode.\n");
                } else {
                    // 进入移动指针模式
                    bit_set(global_data.point_mode, G_PMOD_PMOVE_MASK);
                    uint8_t blink_state = (ticks_ms() / UI_BLINK_MS) % 2; // 该时间段指示条消失
                    if (blink_state) {
                        bit_set(global_data.point_mode, G_PMOD_PBLINK_MASK);
                    } else {
                        bit_clear(global_data.point_mode, G_PMOD_PBLINK_MASK);
                    }
                    printf("Enter Pointer Move Mode.\n");
                }
                ui_com_freq_digital(1, 0);
            }
        } else if (event_value == kp_KEY1) {
            // 切换FM和AM
            if (global_data.rf_mode == G_RF_MODE_AM) {
                global_data.rf_mode = G_RF_MODE_FM;
                global_data.freq = G_FM_FREQ_MIN;
                __switch_to_fm();
            } else {
                global_data.rf_mode = G_RF_MODE_AM;
                global_data.freq = G_AM_FREQ_MIN;
                __switch_to_am();
            }
            ui_com_fm_am(1);
            ui_com_freq_digital(1, 0);
        } else if (event_value == kp_KEY3) {
            if (global_data.volumn < G_VOLUMN_MAX) {
                global_data.volumn += 1;
                __send_volumn();
                ui_com_vol_bar(0);
            }
        } else if (event_value == kp_KEY5) {
            if (global_data.volumn > 0) {
                global_data.volumn -= 1;
                __send_volumn();
                ui_com_vol_bar(0);
            }
        }
    } else if (event_type == kp_LONG_PRESS) {
        if (event_value == kp_KEYENCODER) {
            if (global_data.point_mode & G_PMOD_MODE_MASK) {
                // 退出指针模式
                bit_clear(global_data.point_mode, G_PMOD_MODE_MASK);
                printf("Exit Pointer Mode.\n");
            } else {
                // 进入指针模式
                bit_set(global_data.point_mode, G_PMOD_MODE_MASK);
                bit_clear(global_data.point_mode, G_PMOD_PMOVE_MASK);
                printf("Enter Pointer Mode.\n");
            }
            ui_com_freq_digital(1, 0);
        } else if (event_value == kp_KEY5) {
            if (global_data.flag & G_FL_MUTE) {
                KT0915_setAudioMute(0);
                CLEAR_BIT(global_data.flag, G_FL_MUTE);
            } else {
                KT0915_setAudioMute(1);
                SET_BIT(global_data.flag, G_FL_MUTE);
            }
            ui_com_vol_bar(0);
        }
    } else if (event_type != kp_NOP) {
        printf("event: %u, key: %u\n", event_type, event_value);
    }
    timer_event();
    ui_screen_main_animation();
}
