#include "gpanthera.hh"
#include <iostream>
#include <utility>
#include <libintl.h>
#include <locale.h>
#include <filesystem>
#define _(STRING) gettext(STRING)

namespace gPanthera {
    std::vector<Gtk::Widget*> collect_children(Gtk::Widget &widget) {
        std::vector<Gtk::Widget*> children;
        for(auto *child = widget.get_first_child(); child; child = child->get_next_sibling()) {
            children.push_back(child);
        }
        return children;
    }

    void init() {
        // Set up gettext configuration
        setlocale(LC_ALL, "");

        bindtextdomain("gpanthera", "./locales");
        textdomain("gpanthera");
    }

    DockablePane::DockablePane(std::shared_ptr<LayoutManager> layout, Gtk::Widget &child, const Glib::ustring &name, const Glib::ustring &label, Gtk::Image *icon, DockStack *stack, Gtk::Widget *custom_header)
        : Gtk::Box(Gtk::Orientation::VERTICAL, 0), name(name) {
        if(icon) {
            this->icon = icon;
        }
        if(stack) {
            this->stack = stack;
        }
        this->layout = std::move(layout);
        this->label.set_text(label);
        header = std::make_unique<Gtk::HeaderBar>();
        header->set_show_title_buttons(false);
        if(custom_header) {
            header->set_title_widget(*custom_header);
        } else {
            header->set_title_widget(this->label);
        }
        auto header_menu_button = Gtk::make_managed<Gtk::MenuButton>();
        auto header_menu = Gio::Menu::create();
        header_menu_button->set_direction(Gtk::ArrowType::NONE);
        header_menu_button->set_menu_model(header_menu);

        auto action_group = Gio::SimpleActionGroup::create();
        header_menu_button->insert_action_group("win", action_group);

        // Close action
        auto close_action = Gio::SimpleAction::create("close");
        close_action->signal_activate().connect([this](const Glib::VariantBase&) {
            if(this->stack) {
                this->stack->set_visible_child("empty");
            }
        });
        action_group->add_action(close_action);
        header_menu->append(_("Close"), "win.close");

        // Pop out action
        auto pop_out_action = Gio::SimpleAction::create("pop_out");
        pop_out_action->signal_activate().connect([this](const Glib::VariantBase&) {
            if(this->stack) {
                this->pop_out();
            }
        });
        action_group->add_action(pop_out_action);
        header_menu->append(_("Pop out"), "win.pop_out");

        // Move menu
        auto move_menu = Gio::Menu::create();
        for(auto &this_stack : this->layout->stacks) {
            auto action_name = "move_" + this_stack->name;
            auto move_action = Gio::SimpleAction::create(action_name);
            move_action->signal_activate().connect([this, this_stack](const Glib::VariantBase&) {
                this_stack->add_pane(*this);
            });
            action_group->add_action(move_action);
            move_menu->append(this_stack->name, "win." + action_name);
        }

        // Add move section
        auto move_menu_item = Gio::Menu::create();
        move_menu_item->append_section(_("Move"), move_menu);
        header_menu->append_section({}, move_menu_item);

        header->pack_end(*header_menu_button);

        this->prepend(*header);
        this->child = &child;
        this->append(child);
    }

    void DockablePane::redock(DockStack *stack) {
        if(this->window != nullptr) {
            this->window->hide();
            this->window->unset_titlebar();
            this->window->set_decorated(false);
            this->header->get_style_context()->remove_class("titlebar");
            this->prepend(*this->header);
            this->window->unset_child();
            this->window->close();
        } else if(this->stack == this->get_parent()) {
            this->stack->remove(*this);
        }
        this->stack = stack;
        this->stack->add(*this, this->get_identifier());
        if(this->window != nullptr) {
            this->window->destroy();
            delete this->window;
            this->window = nullptr;
        }
    }

    void DockablePane::pop_out() {
        if(this->stack != nullptr) {
            this->stack->remove(*this);
            this->stack = nullptr;
        }

        if(this->window == nullptr) {
            this->remove(*this->header);
            this->window = new DockWindow(this);
            this->window->set_titlebar(*this->header);
            this->window->set_child(*this);
            this->window->set_decorated(true);
            this->window->present();
        }
    }

    Glib::ustring DockablePane::get_identifier() const {
        return name;
    }

    Gtk::Image *DockablePane::get_icon() const {
        return icon;
    }

    Gtk::Widget *DockablePane::get_child() const {
        return child;
    }

    Gtk::Label *DockablePane::get_label() {
        return &label;
    }

    LayoutManager::LayoutManager() : Glib::ObjectBase("LayoutManager") {
    }

    void LayoutManager::add_pane(DockablePane *pane) {
        panes.push_back(pane);
    }

    void LayoutManager::add_stack(DockStack *stack) {
        stacks.push_back(stack);
    }

    DockStack::DockStack(std::shared_ptr<LayoutManager> layout, const Glib::ustring &name) : Gtk::Stack(), layout(layout), name(name) {
        auto *empty_child = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0);
        add(*empty_child, "empty");
        // Add the stack to a layout manager
        this->layout->add_stack(this);
    }

    DockWindow::DockWindow(DockablePane *pane) {
        this->pane = pane;
        this->set_child(*pane);
    }

    DockStackSwitcher::DockStackSwitcher(DockStack *stack) : Gtk::Box(Gtk::Orientation::HORIZONTAL), stack(stack) {
        auto update_callback = [this](Gtk::Widget*) {
            this->update_buttons();
        };
        stack->signal_child_added.connect(update_callback);
        stack->signal_child_removed.connect(update_callback);
    }

    DockStackSwitcher::~DockStackSwitcher() {
        add_handler.disconnect();
        remove_handler.disconnect();
    }

    DockButton::DockButton(DockablePane *pane) : Gtk::Button(), pane(pane) {
        if(pane->get_icon()) {
            auto new_image = Gtk::make_managed<Gtk::Image>(this->pane->get_icon()->get_paintable());
            this->set_child(*new_image);
        }
        this->set_tooltip_text(pane->get_label()->get_text());
        this->set_halign(Gtk::Align::CENTER);
    }

    void DockStackSwitcher::update_buttons() {
        auto old_buttons = collect_children(*this);
        for(auto *button : old_buttons) {
            remove(*button);
        }
        for(auto *widget = stack->get_first_child(); widget; widget = widget->get_next_sibling()) {
            if(auto pane = dynamic_cast<DockablePane*>(widget)) {
                auto *button = Gtk::make_managed<DockButton>(pane);
                button->signal_clicked().connect([this, pane]() {
                    if(stack->get_visible_child_name() == pane->get_identifier()) {
                        stack->set_visible_child("empty");
                    } else {
                        stack->set_visible_child(pane->get_identifier());
                    }
                });
                if(pane->get_identifier() != Glib::ustring("empty")) {
                    append(*button);
                }
            }
        }
    }

    void DockStack::add_pane(DockablePane &child) {
        child.redock(this);
    }

    void DockStack::add(Gtk::Widget &child, const Glib::ustring &name) {
        Gtk::Stack::add(child, name);
        signal_child_added.emit(&child);
    }

    void DockStack::remove(Gtk::Widget &child) {
        Gtk::Stack::remove(child);
        signal_child_removed.emit(&child);
    }
} // namespace gPanthera
