#include "menu.h"
#include <stdlib.h>
#include <string.h>

menu_state_t state = OFF;
uint8_t selected = 0;

int8_t menu_val_timezone_ee EEMEM;
int8_t menu_val_timezone;
uint8_t menu_val_format_ee EEMEM;
uint8_t menu_val_format;

//void debug_menu(){
//    printf("state:    %d\r\n", state);
//    printf("selected: %d\r\n", selected);
//    printf("timezone: %d\r\n", menu_val_timezone);
//    printf("\r\n");
//}

uint8_t get_menu_active(){
    if(state != OFF)
        return 1;
    return 0;
}

void enter_menu(){
    switch(state){
        case OFF:
            state = 1;
            break;
        case EXIT:
            state = OFF;
            break;
        default:
            selected ^= 1;
            break;
    }
    //debug_menu();
}

const char* get_menu_text(){
    char *res = "      ";

    memset(res, ' ', 6);
    if(selected)
        switch(state){
            case TIMEZONE:
                res = "      ";
                menu_val_timezone = eeprom_read_byte((uint8_t*)&menu_val_timezone_ee);
                if(menu_val_timezone < 0)
                    res[3] = '-';
                else
                    res[3] = ' ';
                res[4] = abs(menu_val_timezone / 10)+0x30;
                res[5] = abs(menu_val_timezone % 10)+0x30;
                break;
            case FORMAT:
                res[2] = (menu_val_format / 10) + 0x30;
                res[3] = (menu_val_format % 10) + 0x30;
                res[4] = 'H';
                break;
            default:
                res = "ERROR";
                break;
        } 
    else
        switch(state){
            case TIMEZONE:
                res = "ZONE  ";
                break;
            case FORMAT:
                res = "FORMAT";
                break;
            case EXIT:
                res = "ZURUEK";
                break;
            default:
                res = "ERROR";
                break;
        } 
    return res;
}

void menu_up_down(uint8_t up_down){
    if(selected)
        switch(state){
            case TIMEZONE:
                menu_val_timezone += up_down;
                if(menu_val_timezone < -12)
                    menu_val_timezone = 12;
                if(menu_val_timezone > 12)
                    menu_val_timezone = -12;
                eeprom_write_byte((uint8_t*)&menu_val_timezone_ee, menu_val_timezone);
                break;
            case FORMAT:
                if(menu_val_format == 12)
                    menu_val_format = 24;
                else if(menu_val_format == 24)
                    menu_val_format = 12;
                break;
            default:
                break;
        } 
    else{
        state += up_down;
        if(state < 1)
            state = EXIT;
        if(state > 3)
            state = TIMEZONE;
    }
    //debug_menu();
}
