#ifndef GASPARDOS_WIDGETS_HPP
#define GASPARDOS_WIDGETS_HPP
#include <stdint.h>
#include <cstring>

namespace gaspardos
{
    namespace gui
    {
        enum Kind
        {
            ButtonKind    = 1,
            TextFieldKind = 2,
            MenuKind      = 3,
            MenuItemKind  = 4,
            LabelKind     = 5
        };

        enum EventType
        {
            Exposure     = 1,
            ButtonDown   = 2,
            ButtonUp     = 3,
            KeyDown      = 8,
            CloseRequest = 15,
            Ready        = 100,
            Error        = 101,
            Overflow     = 102
        };

        struct Event
        {
            int      type, x, y;
            uint32_t buttons, key;
        };

        struct Widget
        {
            Kind kind;
            int  id, x, y, width, height, parent;
            char text[64];

            Widget() : kind(LabelKind), id(0), x(0), y(0), width(0), height(0), parent(0)
            {
                text[0] = 0;
            }

            Widget(Kind k, int ident, int px, int py, int w, int h, const char* label, int menu = 0)
                : kind(k), id(ident), x(px), y(py), width(w), height(h), parent(menu)
            {
                std::strncpy(text, label ? label : "", 63);
                text[63] = 0;
            }
        };

        struct Button : Widget
        {
            Button(int id, int x, int y, int w, int h, const char* label)
                : Widget(ButtonKind, id, x, y, w, h, label)
            {
            }
        };

        struct TextField : Widget
        {
            TextField(int id, int x, int y, int w, int h, const char* value = "")
                : Widget(TextFieldKind, id, x, y, w, h, value)
            {
            }
        };

        struct Menu : Widget
        {
            Menu(int id, int x, int y, int w, int h, const char* title)
                : Widget(MenuKind, id, x, y, w, h, title)
            {
            }
        };

        struct MenuItem : Widget
        {
            MenuItem(int id, int menu, int x, int y, int w, int h, const char* label)
                : Widget(MenuItemKind, id, x, y, w, h, label, menu)
            {
            }
        };

        struct Label : Widget
        {
            Label(int id, int x, int y, int w, int h, const char* label)
                : Widget(LabelKind, id, x, y, w, h, label)
            {
            }
        };

        class Painter
        {
        public:
            virtual ~Painter()
            {
            }

            virtual int64_t fill(int x, int y, int w, int h, uint32_t color)      = 0;
            virtual int64_t text(int x, int y, uint32_t color, const char* value) = 0;
        };

        /* Fixed capacity; ASCII editing at end of field, Tab navigation, Enter activation.
           Return values: positive action ID, 0 no action, -1 close, -2 UI error. */
        class Widgets
        {
            Widget items_[32];
            int    count_, focus_, pressed_, menu_, width_, height_, paintStep_;
            bool   ready_, dirty_;
            Widgets(const Widgets&);
            Widgets& operator=(const Widgets&);

            bool visible(int i) const
            {
                return items_[i].kind != MenuItemKind || items_[i].parent == menu_;
            }

            void changed()
            {
                dirty_     = true;
                paintStep_ = 0;
            }

            int hit(int x, int y) const
            {
                for (int pass = 1; pass >= 0; --pass)
                    for (int i = count_ - 1; i >= 0; --i)
                    {
                        const Widget& w = items_[i];
                        if ((w.kind == MenuItemKind) != static_cast<bool>(pass) || !visible(i)
                            || w.kind == LabelKind)
                            continue;
                        if (x >= w.x && y >= w.y && x - w.x < w.width && y - w.y < w.height)
                            return i;
                    }
                return -1;
            }

            int activate(int i)
            {
                if (i < 0)
                    return 0;
                Widget& w = items_[i];
                if (w.kind == MenuKind)
                {
                    menu_ = menu_ == w.id ? 0 : w.id;
                    changed();
                    return 0;
                }
                if (w.kind == MenuItemKind)
                {
                    menu_  = 0;
                    focus_ = -1;
                    changed();
                }
                return w.id;
            }

            void tab()
            {
                for (int step = 1; step <= count_; ++step)
                {
                    int i = (focus_ + step) % count_;
                    if (visible(i) && items_[i].kind != LabelKind)
                    {
                        focus_ = i;
                        changed();
                        return;
                    }
                }
            }

        public:
            Widgets(int width, int height)
                : items_()
                , count_(0)
                , focus_(-1)
                , pressed_(-1)
                , menu_(0)
                , width_(width)
                , height_(height)
                , paintStep_(0)
                , ready_(false)
                , dirty_(true)
            {
            }

            int add(const Widget& w)
            {
                if (count_ == 32)
                    return -24;
                if (w.id <= 0 || w.width < 16 || w.height < 20 || w.x < 0 || w.y < 0 || w.x > width_
                    || w.y > height_ || w.width > width_ - w.x || w.height > height_ - w.y
                    || w.kind < ButtonKind || w.kind > LabelKind)
                    return -22;
                bool parent = false;
                for (int i = 0; i < count_; ++i)
                {
                    if (items_[i].id == w.id)
                        return -17;
                    if (items_[i].id == w.parent && items_[i].kind == MenuKind)
                        parent = true;
                }
                if ((w.kind == MenuItemKind && !parent) || (w.kind != MenuItemKind && w.parent))
                    return -22;
                items_[count_++] = w;
                changed();
                return 0;
            }

            const char* value(int id) const
            {
                for (int i = 0; i < count_; ++i)
                    if (items_[i].id == id)
                        return items_[i].text;
                return 0;
            }

            int setText(int id, const char* text)
            {
                for (int i = 0; i < count_; ++i)
                    if (items_[i].id == id)
                    {
                        std::strncpy(items_[i].text, text ? text : "", 63);
                        items_[i].text[63] = 0;
                        changed();
                        return 0;
                    }
                return -9;
            }

            int event(const Event& e)
            {
                if (e.type == CloseRequest)
                    return -1;
                if (e.type == Error)
                {
                    ready_ = false;
                    return -2;
                }
                if (e.type == Ready)
                {
                    ready_ = true;
                    changed();
                }
                if (e.type == Exposure || e.type == Overflow)
                {
                    if (e.type == Overflow)
                        pressed_ = -1;
                    changed();
                }
                if (!ready_)
                    return 0;
                if (e.type == ButtonDown && (e.buttons & 1))
                {
                    int i = hit(e.x, e.y);
                    if (menu_
                        && (i < 0 || (items_[i].kind != MenuItemKind && items_[i].id != menu_)))
                    {
                        menu_ = 0;
                        i     = hit(e.x, e.y);
                    }
                    focus_   = i;
                    pressed_ = i;
                    changed();
                }
                if (e.type == ButtonUp && pressed_ >= 0 && !(e.buttons & 1))
                {
                    int i    = pressed_;
                    pressed_ = -1;
                    changed();
                    if (hit(e.x, e.y) == i && items_[i].kind != TextFieldKind)
                        return activate(i);
                }
                if (e.type == KeyDown)
                {
                    if (e.key == 27)
                    {
                        menu_    = 0;
                        pressed_ = -1;
                        changed();
                        return 0;
                    }
                    if (e.key == 9)
                    {
                        tab();
                        return 0;
                    }
                    if (focus_ >= 0 && visible(focus_))
                    {
                        Widget& w = items_[focus_];
                        if (e.key == 13)
                            return activate(focus_);
                        if (w.kind == TextFieldKind)
                        {
                            std::size_t n = std::strlen(w.text);
                            if ((e.key == 8 || e.key == 127) && n)
                            {
                                w.text[n - 1] = 0;
                                changed();
                            }
                            else if (e.key >= 32 && e.key <= 126 && n < 63)
                            {
                                w.text[n]     = static_cast<char>(e.key);
                                w.text[n + 1] = 0;
                                changed();
                            }
                        }
                        else if (e.key == 32)
                            return activate(focus_);
                    }
                }
                return 0;
            }

            bool dirty() const
            {
                return dirty_;
            }

            /* Resume exactly at the failed drawing command on a full kernel UI queue. */
            int64_t paint(Painter& painter)
            {
                if (!ready_)
                    return -11;
                if (!dirty_)
                    return 0;
                if (paintStep_ == 0)
                {
                    int64_t r = painter.fill(0, 0, width_, height_, 0xE8E8E8);
                    if (r < 0)
                        return r;
                    paintStep_ = 1;
                }
                int command = 1;
                for (int pass = 0; pass < 2; ++pass)
                    for (int i = 0; i < count_; ++i)
                    {
                        const Widget& w = items_[i];
                        if (!visible(i) || ((w.kind == MenuItemKind) != static_cast<bool>(pass)))
                            continue;
                        uint32_t border     = i == focus_ ? 0xC06020 : 0x606060;
                        uint32_t background = w.kind == TextFieldKind ? 0xFFFFFF : 0xD8D8D8;
                        if (i == pressed_ || (w.kind == MenuKind && w.id == menu_))
                            background = 0xB0B0B0;
                        if (w.kind == LabelKind)
                            border = background = 0xE8E8E8;
                        char shown[64];
                        int  limit = (w.width - 12) / 8;
                        if (limit > 63)
                            limit = 63;
                        std::size_t length = std::strlen(w.text);
                        const char* start  = w.text;
                        if (w.kind == TextFieldKind && length > static_cast<std::size_t>(limit))
                            start += length - limit;
                        std::strncpy(shown, start, limit);
                        shown[limit] = 0;
                        for (int part = 0; part < 3; ++part, ++command)
                        {
                            if (command < paintStep_)
                                continue;
                            int64_t r =
                                part == 0 ? painter.fill(w.x, w.y, w.width, w.height, border)
                                : part == 1
                                    ? painter.fill(
                                          w.x + 1, w.y + 1, w.width - 2, w.height - 2, background)
                                    : painter.text(w.x + 6, w.y + 4, 0x202020, shown);
                            if (r < 0)
                                return r;
                            ++paintStep_;
                        }
                    }
                dirty_     = false;
                paintStep_ = 0;
                return 0;
            }
        };
    }  // namespace gui
}  // namespace gaspardos
#endif
