#include "treeview.h"
#include "japi/draw.h"
#include "japi/font.h"
#include "japi/input.h"

namespace treeview
{
    int width = 200;
    int scroll = 0;
    int current[2] = {-1, -1};
    int selected[2] = {-1, -1};
    int line = 0;
    int element = 0;
    int max_elements = 0;

    void start()
    {
        draw::setClip(0,48,treeview::width, draw::getWindowSize().y-48);
        draw::setColor(0xff181818);
        draw::fillrect(0,48,treeview::width, draw::getWindowSize().y-48);
        current[0] = current[1] = line = element = 0;

        max_elements = (draw::getWindowSize().y-48) / 24;
        int mx = input::mouseX();
        int my = input::mouseY();
        if (mx>=0 && my>=48 && mx<treeview::width && my<draw::getWindowSize().y) {
            scroll -= input::mouseWheel();
            if (scroll < 0) scroll = 0;
        }

    }

    bool option(const char* label, const int level)
    {
        if (element>=scroll && line<max_elements) {
            int mx = input::mouseX();
            int my = input::mouseY();
            const int opt_y = (48+line*24);
            if (mx>=0 && my>=opt_y && mx<treeview::width && my<opt_y+24) {
                if (input::mouseClk(input::mouse::button::left)) {
                    input::mouseDiscard();
                    selected[level] = current[level];
                    if (level<1) selected[level+1] = -1;
                }
                draw::setColor(selected[level]==current[level] ? 0xff37373d : 0xff2a2d2e);
                draw::fillrect(0, opt_y, treeview::width, 24);
            } else if (selected[level] == current[level]) {
                draw::setColor(0xff37373d);
                draw::fillrect(0, opt_y, treeview::width, 24);
            }
            font::print(label, 8+16*level, opt_y+8);
            line++;
        }
        current[level]++;
        element++;

        return selected[level]==current[level]-1;
    }

    void end()
    {
        draw::resetClip();
        if (element>max_elements && line<max_elements) {
            scroll -= max_elements-line;
        }
    }

    const int getSelected(const int level)
    {
        return selected[level];
    }
}
