#include "CMenu.h"

void CMenu::add_subitem(int n, char *_text)
{
    item[n].add_subitem(_text);
}

void CMenu::do_menu(void)
{
    int old_selected=selected;

    if(key[KEY_UP])
    {
        if(is_keypressed==false)
        {
            selected--;
        }
        is_keypressed=true;
    }
    else if(key[KEY_DOWN])
    {
        if(is_keypressed==false)
        {
            selected++;
        }
        is_keypressed=true;
    }
    else if(key[KEY_LEFT])
    {
        if(is_keypressed==false)
        {
            item[selected].change_subitem(-1);
        }
        is_keypressed=true;
    }
    else if(key[KEY_RIGHT])
    {
        if(is_keypressed==false)
        {
            item[selected].change_subitem(1);
        }
        is_keypressed=true;
    }
    else
        is_keypressed=false;
        
        
    if(selected>=number_of_menu_items)
        selected=0;
    else if(selected<0)
        selected=number_of_menu_items-1;
        
    if(selected!=old_selected)
    {
        item[selected].toggle_selected();
        item[old_selected].toggle_selected();
    }    
}

void CMenu::draw_menu(BITMAP *backgr, float offsetx, float offsety)
{
    for(int n=0 ; n<number_of_menu_items; n++)
    {
        item[n].draw_item(backgr,offsetx,offsety);
    }
}

void CMenu::add_menu_item(char *_text, itemInfo _info, float _x, float _y)
{
    if(number_of_menu_items<MAXMENUITEMS)
    {
        item[number_of_menu_items].set_item_text(_text,_info,_x,_y);
        
        if(number_of_menu_items==0) //is the first element in the menu
            item[0].toggle_selected();
        number_of_menu_items++;
    }
}

void CMenu::init(void)
{
    number_of_menu_items=0;
    selected=0;
    is_keypressed=false;
    for(int n=0 ; n<MAXMENUITEMS; n++)
    {
        item[n].init();
    }
}
