#include "gpanthera.hh"
#include <gtkmm.h>
#include <glibmm.h>
#include <glibmm/ustring.h>
#include <iostream>
#include <memory>
#include <libintl.h>
#include <locale.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <webkit/webkit.h>
#include <fstream>
#include <nlohmann/json.hpp>
#include <iomanip>
#include <sstream>
#include <dlfcn.h>
#include "plugin_api.h"

using plugin_entrypoint_type = void(*)(void);

std::string url_encode(const std::string &value) {
    // Thanks https://stackoverflow.com/a/17708801
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;

    for(char c : value) {
        // Keep alphanumeric and other accepted characters intact
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
            continue;
        }

        // Any other characters are percent-encoded
        escaped << std::uppercase;
        escaped << '%' << std::setw(2) << int((unsigned char) c);
        escaped << std::nouppercase;
    }

    return escaped.str();
}

struct SearchEngine {
    Glib::ustring name;
    Glib::ustring url;
    Glib::ustring get_search_url(const std::string &query) {
        auto pos = url.find("%s");
        if(pos == Glib::ustring::npos) {
            throw std::runtime_error("Invalid search engine URL: missing '%s' placeholder");
        }
        auto new_url = url;
        new_url.replace(pos, 2, url_encode(query));
        return new_url;
    }
};

class PantheraWww : public Gtk::Application {
    Gtk::Window *window = Gtk::make_managed<Gtk::Window>();
protected:
    std::shared_ptr<gPanthera::LayoutManager> layout_manager;
    std::shared_ptr<gPanthera::ContentManager> content_manager;
    Gtk::Entry *url_bar = nullptr;
    std::string cookie_file = "cookies.txt";
    std::vector<SearchEngine> search_engines;
    SearchEngine *default_search_engine = nullptr;

    static void notify_callback(GObject *object, GParamSpec *pspec, gpointer data) {
        if(!gtk_widget_get_parent(GTK_WIDGET(object))) {
            return;
        }
        auto parent = gtk_widget_get_parent(gtk_widget_get_parent(GTK_WIDGET(object)));
        if(auto page = dynamic_cast<gPanthera::ContentPage*>(Glib::wrap(parent))) {
            if(g_strcmp0(pspec->name, "title") == 0) {
                if(auto label = dynamic_cast<Gtk::Label*>(page->tab_widget->get_last_child())) {
                    if(strlen(webkit_web_view_get_title(WEBKIT_WEB_VIEW(object))) == 0) {
                        label->set_label("Untitled");
                    } else {
                        label->set_label(webkit_web_view_get_title(WEBKIT_WEB_VIEW(object)));
                    }
                }
            } else if(g_strcmp0(pspec->name, "favicon") == 0) {
                // Update favicons
                if(auto image = dynamic_cast<Gtk::Image*>(page->tab_widget->get_first_child())) {
                    image->set_from_icon_name("image-loading-symbolic");
                    if(auto favicon = webkit_web_view_get_favicon(WEBKIT_WEB_VIEW(object))) {
                        if(G_IS_OBJECT(favicon)) {
                            if(Glib::RefPtr<Gdk::Texture> texture = Glib::wrap(favicon)) {
                                image->set(texture);
                            }
                        }
                    }
                }
            }
        }
    }

    static void notify_focused_callback(GObject *object, GParamSpec *pspec, gpointer data) {
        if(!gtk_widget_get_parent(GTK_WIDGET(object))) {
            return;
        }
        auto this_ = static_cast<PantheraWww*>(data);
        auto parent = gtk_widget_get_parent(gtk_widget_get_parent(GTK_WIDGET(object)));
        if(auto page = dynamic_cast<gPanthera::ContentPage*>(Glib::wrap(parent))) {
            if(g_strcmp0(pspec->name, "uri") == 0) {
                this_->url_bar->set_text(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(object)));
            }
        }
    }

    static void on_back_pressed(GtkGestureClick *gesture, int n_press, double x, double y, gpointer user_data) {
        WebKitWebView *webview = WEBKIT_WEB_VIEW(user_data);
        webkit_web_view_go_back(webview);
    }

    static void on_forward_pressed(GtkGestureClick *gesture, int n_press, double x, double y, gpointer user_data) {
        WebKitWebView *webview = WEBKIT_WEB_VIEW(user_data);
        webkit_web_view_go_forward(webview);
    }

    static gboolean on_decide_policy(WebKitWebView *source, WebKitPolicyDecision *decision, WebKitPolicyDecisionType type, gpointer user_data) {
        // Middle-click opens in a new window
        if(auto self = static_cast<PantheraWww*>(user_data)) {
            if(type == WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION) {
                auto action = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(decision));
                if(webkit_navigation_action_get_mouse_button(action) == 2) {
                    Glib::ustring url = Glib::ustring(webkit_uri_request_get_uri(webkit_navigation_action_get_request(action)));
                    self->on_new_tab(nullptr, url, false);
                    webkit_policy_decision_ignore(decision);
                    return true;
                }
            } else if(type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) {
                auto action = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(decision));
                self->on_new_tab(nullptr, webkit_uri_request_get_uri(webkit_navigation_action_get_request(action)), false, true);
                return true;
            }
        }
        return false;
    }

    void on_new_tab(gPanthera::ContentStack *stack, const Glib::ustring &url = "about:blank", bool focus = true, bool new_window = false) {
        if(!stack) {
            // Find the current area
            stack = content_manager->get_last_operated_page()->get_stack();
        }

        WebKitWebView *webview = WEBKIT_WEB_VIEW(webkit_web_view_new());
        gtk_widget_set_hexpand(GTK_WIDGET(webview), true);
        gtk_widget_set_vexpand(GTK_WIDGET(webview), true);
        auto page_content = Gtk::make_managed<Gtk::Box>();
        gtk_box_append(page_content->gobj(), GTK_WIDGET(webview));
        auto page_tab = new Gtk::Box();
        page_tab->set_orientation(Gtk::Orientation::HORIZONTAL);
        auto initial_icon = Gtk::make_managed<Gtk::Image>(Gio::Icon::create("image-loading-symbolic"));
        page_tab->append(*initial_icon);
        page_tab->append(*Gtk::make_managed<Gtk::Label>("Untitled"));
        page_tab->set_spacing(4);
        auto page = Gtk::make_managed<gPanthera::ContentPage>(content_manager, stack, page_content, page_tab);
        g_signal_connect(webview, "notify", G_CALLBACK(notify_callback), page->gobj());
        g_signal_connect(webview, "decide-policy", G_CALLBACK(on_decide_policy), this);
        webkit_web_view_load_uri(webview, url.data());
        auto cookie_manager = webkit_network_session_get_cookie_manager(webkit_web_view_get_network_session(webview));
        webkit_cookie_manager_set_persistent_storage(cookie_manager, cookie_file.c_str(), WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
        webkit_cookie_manager_set_accept_policy(cookie_manager, WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS);
        auto website_data_manager = webkit_network_session_get_website_data_manager(webkit_web_view_get_network_session(webview));
        webkit_website_data_manager_set_favicons_enabled(website_data_manager, true);
        GtkEventController *click_controller_back = GTK_EVENT_CONTROLLER(gtk_gesture_click_new());
        gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(click_controller_back), 8);
        g_signal_connect(click_controller_back, "pressed", G_CALLBACK(on_back_pressed), webview);
        gtk_widget_add_controller(GTK_WIDGET(webview), click_controller_back);

        GtkEventController *click_controller_forward = GTK_EVENT_CONTROLLER(gtk_gesture_click_new());
        gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(click_controller_forward), 9);
        g_signal_connect(click_controller_forward, "pressed", G_CALLBACK(on_forward_pressed), webview);
        gtk_widget_add_controller(GTK_WIDGET(webview), click_controller_forward);

        stack->add_page(*page);
        if(focus) {
            stack->set_visible_child(*page);
            content_manager->set_last_operated_page(page);
        }
        if(new_window) {
            bool result = stack->signal_detach.emit(page);
        }
    }

    void on_startup() override {
        Gtk::Application::on_startup();
        add_window(*window);
        window->set_default_size(600, 400);
        layout_manager = std::make_shared<gPanthera::LayoutManager>();
        auto dock_stack_1 = Gtk::make_managed<gPanthera::DockStack>(layout_manager, "One", "one");
        auto switcher_1 = Gtk::make_managed<gPanthera::DockStackSwitcher>(dock_stack_1, Gtk::Orientation::HORIZONTAL);
        auto dock_stack_2 = Gtk::make_managed<gPanthera::DockStack>(layout_manager, "Two", "two");
        auto switcher_2 = Gtk::make_managed<gPanthera::DockStackSwitcher>(dock_stack_2, Gtk::Orientation::VERTICAL);
        auto pane_1_content = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0);
        auto debug_button = Gtk::make_managed<Gtk::Button>("Debug");
        pane_1_content->append(*debug_button);
        auto pane_2_content = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0);
        auto test_notebook = Gtk::make_managed<Gtk::Notebook>();
        test_notebook->append_page(*Gtk::make_managed<Gtk::Label>("Test 1"), *Gtk::make_managed<Gtk::Label>("Test 1"));
        pane_2_content->append(*test_notebook);
        auto pane_3_content = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0);
        pane_3_content->append(*Gtk::make_managed<Gtk::Label>("Pane 3 content"));
        auto pane_1_icon = Gtk::make_managed<Gtk::Image>();
        pane_1_icon->set_from_icon_name("go-home-symbolic");
        auto pane_2_icon = Gtk::make_managed<Gtk::Image>();
        pane_2_icon->set_from_icon_name("folder-symbolic");
        auto pane_3_icon = Gtk::make_managed<Gtk::Image>();
        pane_3_icon->set_from_icon_name("network-transmit-receive-symbolic");
        auto pane_1 = Gtk::make_managed<gPanthera::DockablePane>(layout_manager, *pane_1_content, "pane1", "Pane 1", pane_1_icon);
        auto pane_2 = Gtk::make_managed<gPanthera::DockablePane>(layout_manager, *pane_2_content, "pane2", "Pane 2", pane_2_icon);
        auto pane_3 = Gtk::make_managed<gPanthera::DockablePane>(layout_manager, *pane_3_content, "pane3", "Pane 3", pane_3_icon);

        dock_stack_1->set_transition_type(Gtk::StackTransitionType::SLIDE_LEFT_RIGHT);
        dock_stack_1->set_transition_duration(125);
        dock_stack_1->set_expand(true);
        dock_stack_2->set_transition_type(Gtk::StackTransitionType::SLIDE_UP_DOWN);
        dock_stack_2->set_transition_duration(125);
        dock_stack_2->set_expand(true);

        auto outer_grid = Gtk::make_managed<Gtk::Grid>();
        outer_grid->attach(*switcher_2, 0, 1, 1, 1);
        outer_grid->attach(*switcher_1, 1, 2, 1, 1);
        auto outer_paned = Gtk::make_managed<Gtk::Paned>(Gtk::Orientation::HORIZONTAL);
        outer_paned->set_start_child(*dock_stack_2);
        auto inner_paned = Gtk::make_managed<Gtk::Paned>(Gtk::Orientation::VERTICAL);
        auto content = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0);
        content_manager = std::make_shared<gPanthera::ContentManager>();
        std::function<bool(gPanthera::ContentPage*)> detach_handler;
        detach_handler = [](gPanthera::ContentPage *widget) {
            auto new_stack = Gtk::make_managed<gPanthera::ContentStack>(widget->content_manager, widget->get_stack()->get_detach_handler());
            auto new_switcher = Gtk::make_managed<gPanthera::ContentTabBar>(new_stack, Gtk::Orientation::HORIZONTAL, dynamic_cast<gPanthera::ContentTabBar*>(widget->get_stack()->get_parent()->get_first_child())->get_extra_child_function());
            auto new_notebook = Gtk::make_managed<gPanthera::ContentNotebook>(new_stack, new_switcher);
            auto window = new gPanthera::ContentWindow(new_notebook);
            widget->redock(new_stack);
            window->present();
            new_stack->signal_leave_empty.connect([window]() {
                window->close();
                delete window;
            });
            return true;
        };

        auto return_extra_child = [this](gPanthera::ContentTabBar *switcher) {
            auto new_tab_button = Gtk::make_managed<Gtk::Button>();
            new_tab_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("list-add-symbolic")));
            new_tab_button->set_tooltip_text("New tab");
            new_tab_button->signal_clicked().connect([this, switcher]() {
                on_new_tab(switcher->get_stack());
            });
            return new_tab_button;
        };
        auto content_stack = Gtk::make_managed<gPanthera::ContentStack>(content_manager, detach_handler);
        auto content_stack_switcher = Gtk::make_managed<gPanthera::ContentTabBar>(content_stack, Gtk::Orientation::HORIZONTAL, return_extra_child);
        content_manager->add_stack(content_stack);
        WebKitWebView *webview = WEBKIT_WEB_VIEW(webkit_web_view_new());   // for some reason, this has to be created
        content->set_name("content_box");
        auto content_notebook = Gtk::make_managed<gPanthera::ContentNotebook>(content_stack, content_stack_switcher, Gtk::PositionType::TOP);
        content->append(*content_notebook);
        inner_paned->set_start_child(*content);
        inner_paned->set_end_child(*dock_stack_1);
        outer_paned->set_end_child(*inner_paned);
        outer_grid->attach(*outer_paned, 1, 1, 1, 1);

        // Get search engines
        std::ifstream search_engines_file_in("search_engines.json");
        if(search_engines_file_in) {
            std::string search_engines_json((std::istreambuf_iterator<char>(search_engines_file_in)), std::istreambuf_iterator<char>());
            search_engines_file_in.close();
            set_search_engines_from_json(search_engines_json);
        } else {
            search_engines_file_in.close();
            auto empty_json = nlohmann::json::array();
            std::ofstream search_engines_file_out("search_engines.json");
            search_engines_file_out << empty_json.dump(4);
        }

        // Create the toolbar
        auto main_toolbar = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL, 8);
        // URL bar
        url_bar = Gtk::make_managed<Gtk::Entry>();
        url_bar->set_placeholder_text("Enter URL");
        url_bar->set_hexpand(true);
        auto load_url_callback = [this]() {
            auto page = content_manager->get_last_operated_page();
            bool has_protocol = url_bar->get_text().find("://") != std::string::npos;
            if(!has_protocol) {
                url_bar->set_text("http://" + url_bar->get_text());
            }
            if(page) {
                if(auto webview = WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())) {
                    webkit_web_view_load_uri(webview, url_bar->get_text().c_str());
                }
            }
        };
        // Go
        auto go_button = Gtk::make_managed<Gtk::Button>("Go");
        go_button->signal_clicked().connect(load_url_callback);
        url_bar->signal_activate().connect(load_url_callback);
        content_manager->signal_page_operated.connect([this](gPanthera::ContentPage *page) {
            if(!page->get_child()) {
                return;
            }
            if(!page->get_child()->get_first_child()) {
                return;
            }
            url_bar->set_text(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())));
            guint url_update_handler = g_signal_connect(page->get_child()->get_first_child()->gobj(), "notify", G_CALLBACK(notify_focused_callback), this);
            std::shared_ptr<sigc::connection> control_signal_handler = std::make_shared<sigc::connection>();
            *control_signal_handler = page->signal_control_status_changed.connect([this, page, control_signal_handler, url_update_handler](bool controlled) {
                if(!controlled) {
                    control_signal_handler->disconnect();
                    if(page->get_child() && page->get_child()->get_first_child() && WEBKIT_IS_WEB_VIEW(page->get_child()->get_first_child()->gobj())) {
                        g_signal_handler_disconnect(page->get_child()->get_first_child()->gobj(), url_update_handler);
                    }
                }
            });
        });
        // Back, forward, reload
        auto back_button = Gtk::make_managed<Gtk::Button>();
        back_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-previous-symbolic")));
        back_button->set_tooltip_text("Back");
        auto forward_button = Gtk::make_managed<Gtk::Button>();
        forward_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-next-symbolic")));
        forward_button->set_tooltip_text("Forward");
        auto reload_button = Gtk::make_managed<Gtk::Button>();
        reload_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("view-refresh-symbolic")));
        reload_button->set_tooltip_text("Reload");
        back_button->signal_clicked().connect([this]() {
            auto page = content_manager->get_last_operated_page();
            if(page) {
                if(auto webview = WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())) {
                    webkit_web_view_go_back(webview);
                }
            }
        });
        forward_button->signal_clicked().connect([this]() {
            auto page = content_manager->get_last_operated_page();
            if(page) {
                if(auto webview = WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())) {
                    webkit_web_view_go_forward(webview);
                }
            }
        });
        reload_button->signal_clicked().connect([this]() {
            auto page = content_manager->get_last_operated_page();
            if(page) {
                if(auto webview = WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())) {
                    webkit_web_view_reload(webview);
                }
            }
        });
        // Search bar
        // TODO: provide history, provide a menu button with the other engines
        auto search_bar = Gtk::make_managed<Gtk::Entry>();
        search_bar->set_placeholder_text("Search");
        search_bar->set_hexpand(true);
        if(search_engines.empty()) {
            search_bar->set_sensitive(false);
            search_bar->set_placeholder_text("No search");
        }
        auto search_callback = [this, search_bar, content_stack]() {
            // Create a new tab with the search results
            if(content_manager->get_last_operated_page()) {
                on_new_tab(nullptr);
            } else {
                on_new_tab(content_stack);
            }
            auto page = content_manager->get_last_operated_page();
            if(page) {
                if(auto webview = WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())) {
                    auto search_url = default_search_engine->get_search_url(search_bar->get_text());
                    webkit_web_view_load_uri(webview, search_url.c_str());
                }
            }
        };
        if(default_search_engine) {
            search_bar->signal_activate().connect(search_callback);
        }
        // Assemble the toolbar
        main_toolbar->append(*back_button);
        main_toolbar->append(*forward_button);
        main_toolbar->append(*reload_button);
        main_toolbar->append(*url_bar);
        main_toolbar->append(*go_button);
        main_toolbar->append(*search_bar);
        if(default_search_engine) {
            auto search_button = Gtk::make_managed<Gtk::Button>(default_search_engine->name);
            search_button->signal_clicked().connect(search_callback);
            main_toolbar->append(*search_button);
        }
        outer_grid->attach(*main_toolbar, 0, 0, 2, 1);
        window->set_child(*outer_grid);
        debug_button->signal_clicked().connect([this]() {
            if(content_manager->get_last_operated_page()) {
                std::cout << "Last operated page: " << content_manager->get_last_operated_page()->get_name() << std::endl;
            } else {
                std::cout << "No page operated!" << std::endl;
            }
        });
        // TODO: Use the last operated page and allow opening tabs next to the last operated page using certain panes
        // Load the existing layout, if it exists
        std::ifstream layout_file_in("layout.json");
        if(layout_file_in) {
            std::string layout_json((std::istreambuf_iterator<char>(layout_file_in)), std::istreambuf_iterator<char>());
            layout_file_in.close();
            layout_manager->restore_json_layout(layout_json);
        } else {
            // Create a new layout if the file doesn't exist
            layout_file_in.close();

            dock_stack_1->add_pane(*pane_1);
            dock_stack_1->add_pane(*pane_3);
            dock_stack_2->add_pane(*pane_2);

            std::ofstream layout_file_out("layout.json");
            layout_file_out << layout_manager->get_layout_as_json();
            layout_file_out.close();
        }
        // Save the layout when changed
        layout_manager->signal_pane_moved.connect([this](gPanthera::DockablePane *pane) {
            std::ofstream layout_file_out("layout.json");
            layout_file_out << layout_manager->get_layout_as_json();
            layout_file_out.close();
            std::cout << "Layout changed: " << layout_manager->get_layout_as_json() << std::endl;
        });

        auto new_tab_action = Gio::SimpleAction::create("new_tab");
        new_tab_action->signal_activate().connect([this](const Glib::VariantBase&) {
            on_new_tab(nullptr);
        });
        add_action(new_tab_action);
        set_accels_for_action("app.new_tab", {"<Primary>T"});
        auto close_tab_action = Gio::SimpleAction::create("close_tab");
        close_tab_action->signal_activate().connect([this](const Glib::VariantBase&) {
            auto page = content_manager->get_last_operated_page();
            if(page) {
                page->close();
            }
        });
        add_action(close_tab_action);
        set_accels_for_action("app.close_tab", {"<Primary>W"});

        // Load plugins
        std::ifstream plugin_file_in("plugins.json");
        if(plugin_file_in) {
            std::string plugin_json((std::istreambuf_iterator<char>(plugin_file_in)), std::istreambuf_iterator<char>());
            plugin_file_in.close();
            auto json = nlohmann::json::parse(plugin_json);
            for(auto &plugin : json) {
                auto plugin_path = plugin["path"].get<std::string>();
                load_plugin(plugin_path);
            }
        } else {
            plugin_file_in.close();
            auto empty_json = nlohmann::json::array();
            std::ofstream plugin_file_out("plugins.json");
            plugin_file_out << empty_json.dump(4);
            plugin_file_out.close();
        }
    }

    void on_activate() override {
        window->present();
    }

    void set_search_engines_from_json(const std::string &json_string) {
        auto json = nlohmann::json::parse(json_string);
        Glib::ustring default_search_engine_name;
        for(auto &engine : json) {
            SearchEngine search_engine;
            search_engine.name = engine["name"].get<std::string>();
            search_engine.url = engine["url"].get<std::string>();
            search_engines.push_back(search_engine);
            if(engine.contains("default") && engine["default"].get<bool>()) {
                default_search_engine_name = engine["name"].get<std::string>();
            }
        }
        for(auto &search_engine : search_engines) {
            if(search_engine.name == default_search_engine_name) {
                default_search_engine = &search_engine;
                break;
            }
        }
    }
public:
    static Glib::RefPtr<PantheraWww> create() {
        return Glib::make_refptr_for_instance<PantheraWww>(new PantheraWww());
    }

    std::shared_ptr<gPanthera::LayoutManager> get_layout_manager() {
        return layout_manager;
    }

    std::shared_ptr<gPanthera::ContentManager> get_content_manager() {
        return content_manager;
    }

    void load_plugin(const std::string &plugin_path) {
        void *handle = dlopen(plugin_path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
        if(!handle) {
            std::cerr << "Failed to load plugin: " << dlerror() << std::endl;
            return;
        }
        auto entrypoint = (plugin_entrypoint_type)dlsym(handle, "plugin_init");
        if(!entrypoint) {
            std::cerr << "Failed to find entrypoint in plugin: " << dlerror() << std::endl;
            dlclose(handle);
            return;
        }
        entrypoint();
    }
};

Glib::RefPtr<PantheraWww> app = nullptr;

extern "C" {
    void panthera_log(const char *message) {
        std::cerr << message << std::endl;
    }

    void panthera_add_pane(const char *id, const char *label, GtkImage *icon, GtkWidget *pane) {
        auto pane_child = Glib::wrap(pane);
        auto icon_cc = Glib::wrap(icon);
        auto label_cc = Glib::ustring(label);
        auto id_cc = Glib::ustring(id);
        auto new_pane = Gtk::make_managed<gPanthera::DockablePane>(app->get_layout_manager(), *pane_child, id_cc, label_cc, icon_cc);
        app->get_layout_manager()->add_pane(new_pane);
    }
}

int main(int argc, char *argv[]) {
    gPanthera::init();
    app = PantheraWww::create();
    return app->run(argc, argv);
}