#include "common.h"

int gHistoryScrollTop = 0;
int gHistoryCursor = -1;

void cmdline_history_view()
{
    const int maxx = mgetmaxx();
    const int maxy = mgetmaxy();

    int line = 0;
    for(int i= gHistoryScrollTop; i<vector_size(gHCandidate); i++) {
        string_obj* item = (string_obj*)vector_item(gHCandidate, i);
        
        char* buf = (char*)MALLOC(sizeof(char)*(string_length(item)+1));
        sprintf(buf, "%s", string_c_str(item));

        char* tmp = (char*)MALLOC(sizeof(char)*(maxx+1));
        if(gKanjiCode == kUtf8)
            str_cut2(buf, maxx-1, tmp, maxx);
        else
            cut(buf, tmp, maxx-1);

        if(gHistoryCursor == i) mattron(kCAReverse);        
        mmvprintw(line, 0, "%s", tmp);
        if(gHistoryCursor == i) mattroff();
        line++;
        
        FREE(tmp);
        FREE(buf);

        if(line >= maxy-2) {
            break;
        }
    }
}

void cmdline_history_input(int meta, int key)
{
    if(key == 14 || key == KEY_DOWN) {    // CTRL-N
        gHistoryCursor++;
    }
    else if(key == 16 || key == KEY_UP) {    //CTRL-P
        gHistoryCursor--;
    }
    if(key == 6 || key == KEY_RIGHT) {    // CTRL-F
        gHistoryCursor++;
    }
    else if(key == 2 || key == KEY_LEFT) {    // CTRL-B
        gHistoryCursor--;
    }
    else if(key == 10 || key == 13) {		// CTRL-J CTRL-M
        string_obj* str = (string_obj*) vector_item(gCmdLine, gCLCursor);
        char* cstr = string_c_str(str);

        /// ヒストリーを編集するならコピーを末尾に作成 ///
        if(gCLCursor != vector_size(gCmdLine)-1) {
            cmdline_delete_last_str_if_length_0();
            
            vector_add(gCmdLine, string_new(cstr));
            gCLCursor = vector_size(gCmdLine) -1;

            str = (string_obj*)vector_item(gCmdLine, gCLCursor);
            cstr = string_c_str(str);
        }

        /// ヒストリを挿入 ///
        string_obj* candidate = (string_obj*)vector_item(gHCandidate, gHistoryCursor);
        string_put(str, string_c_str(candidate));

        gCursor = string_length(candidate);

        vector_clear(gHCandidate);
    }
    else if(key == 4 || key==22 || key == KEY_NPAGE) {    // CTRL-D CTRL-V
        gHistoryCursor+=5;
    }
    else if(key == 21 || meta==1&&key=='v' || key == KEY_PPAGE) {    // CTRL-U Meta-v
        gHistoryCursor-=5;
    }
    else if(key == 3 || key == 7 || key == 27) { // CTRL-C CTRL-G Escape
        vector_clear(gHCandidate);
    }

    if(gHistoryCursor < 0) {
        gHistoryCursor = 0;
    }
    if(gHistoryCursor >= vector_size(gHCandidate)) {
        gHistoryCursor = vector_size(gHCandidate)-1;
    }

    const int maxy = mgetmaxy();
    if(gHistoryCursor < gHistoryScrollTop) {
        gHistoryScrollTop = (gHistoryCursor/(maxy-2))*(maxy-2);
    }
    if(gHistoryCursor > gHistoryScrollTop + maxy-3) {
        gHistoryScrollTop = (gHistoryCursor/(maxy-2))*(maxy-2);
    }
}
