#include "common.h"

cMenu* gActiveMenu;
hash_obj* gMenu;

void cMenu::Init()
{
    gMenu = hash_new(10);
}

void cMenu::Final()
{
TBEGIN();

    for(hash_it* i=gMenu->mEntryIt; i; i=i->mNextIt) {
        delete (cMenu*)i->mItem;
    }
    hash_delete(gMenu);

TEND();    
}

cMenu::cMenu(char* title)
{
TBEGIN();

    strcpy(mTitle, title);

    mCursor = 0;

    mMenuItems = vector_new(10);

TEND();    
}

cMenu::~cMenu()
{
    for(int i=0; i<vector_size(mMenuItems); i++) {
        delete (sMenuItem*)vector_item(mMenuItems, i);
    }
    vector_delete(mMenuItems);
}

void cMenu::Append(char* name, int key, char* cmd)
{
TBEGIN();

    char buf[256];
    sprintf(buf, " %-40s", name);
    vector_add(mMenuItems, new sMenuItem(buf, key, cmd));

TEND();    
}

void cMenu::Input(int meta, int key)
{
TBEGIN();

    if(key == 1 || key == KEY_HOME) {        // CTRL-A
        mCursor = 0;
    }
    else if(key == 5 || key == KEY_END) {    // CTRL-E
        mCursor = vector_size(mMenuItems)-1;
    }
    else if(key == 14 || key == KEY_DOWN) {    // CTRL-N
        mCursor++;

        if(mCursor >= vector_size(mMenuItems)) {
            mCursor = 0;
        }
    }
    else if(key == 16 || key == KEY_UP) {    // CTRL-P
        mCursor--;

        if(mCursor < 0) {
            mCursor = vector_size(mMenuItems)-1;
        }
    }
    else if(key == 3 || key == 7 || key == 27) {    // CTRL-C CTRL-G Escape
        gActiveMenu = NULL;
        mclear();
    }
    else if(key == 10 || key == 13) {    // CTRL-M CTRL-J
        gActiveMenu = NULL;
        
        sMenuItem* item = (sMenuItem*)vector_item(mMenuItems, mCursor);
        rb_eval_string(item->mCmd);

        mclear();
    }
    else if(key == 12) {// CTRL-L
        gLDir->Reread();
        gRDir->Reread();
        
        mclear();
        mclear_immediately();
        mrefresh();
    }
    else {
        gActiveMenu = NULL;
        
        for(int i=0; i<vector_size(mMenuItems); i++) {
            sMenuItem* item = (sMenuItem*)vector_item(mMenuItems, i);
            
            if(item->mKey == key) {
                rb_eval_string(item->mCmd);
            }
        }
        
        mclear();
    }

TEND();    
}

void cMenu::View()
{
TBEGIN();

    const int maxx = mgetmaxx();
    const int maxy = mgetmaxy();

    mbox(0, 2, 43, vector_size(mMenuItems) + 2);

    mattron(kCABold);
    mmvprintw(0, 4, mTitle);
    mattroff();

    for(int i=0; i<vector_size(mMenuItems); i++) {
        sMenuItem* item = (sMenuItem*)vector_item(mMenuItems, i);
        
        if(i == mCursor) {
            mattron(kCAReverse);
            mmvprintw(i+1, 3, item->mName);
            mattroff();
        }
        else  {
            mmvprintw(i+1, 3, item->mName);
        }
    }

    mmove_immediately(maxy-1, maxx-1);
    mrefresh();
    
TEND();    
}

void cMenu::Show()
{
TBEGIN();

    mCursor = 0;
    
    
    
View();



    
TEND();
}
