#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 "external/sqlite_orm/sqlite_orm.h"
//#include "plugin_api.h"
#define _(STRING) gettext(STRING)

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();
}

bool starts_with(const Glib::ustring &str, const Glib::ustring &prefix) {
    return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0;
}

bool ends_with(const Glib::ustring &str, const Glib::ustring &suffix) {
    return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}

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;
    }
};

struct HistoryEntry {
    int id;
    std::string url, title;
    int64_t timestamp;
};

using StorageType = decltype(sqlite_orm::make_storage("",
    sqlite_orm::make_table("history",
        sqlite_orm::make_column("id", &HistoryEntry::id, sqlite_orm::primary_key()),
        sqlite_orm::make_column("url", &HistoryEntry::url),
        sqlite_orm::make_column("title", &HistoryEntry::title),
        sqlite_orm::make_column("timestamp", &HistoryEntry::timestamp)
    )
));

class HistoryManager {
public:
    static auto make_storage(const std::string& path) {
        return sqlite_orm::make_storage(path,
            sqlite_orm::make_table("history",
                sqlite_orm::make_column("id", &HistoryEntry::id, sqlite_orm::primary_key()),
                sqlite_orm::make_column("url", &HistoryEntry::url),
                sqlite_orm::make_column("title", &HistoryEntry::title),
                sqlite_orm::make_column("timestamp", &HistoryEntry::timestamp)
            )
        );
    }
    StorageType storage;
    explicit HistoryManager(const std::string &db_path) : storage(make_storage(db_path)) {
        storage.sync_schema();
    }

    void log_url(const std::string &url, const std::string title, const int64_t timestamp = Glib::DateTime::create_now_local().to_unix()) {
        storage.insert(HistoryEntry{-1, url, title, timestamp});
    }

    std::vector<HistoryEntry> get_history() {
        return storage.get_all<HistoryEntry>();
    }

    std::vector<HistoryEntry> get_history_between(int64_t start_time, int64_t end_time) {
        using namespace sqlite_orm;
        return storage.get_all<HistoryEntry>(
            where(c(&HistoryEntry::timestamp) >= start_time and c(&HistoryEntry::timestamp) < end_time),
            order_by(&HistoryEntry::timestamp).desc()
        );
    }
};

class HistoryViewer : public gPanthera::DockablePane {
protected:
    std::shared_ptr<HistoryManager> history_manager;
    Gtk::Calendar *calendar;
    Gtk::Label *date_label;
    Gtk::Box *box_place;
public:
    sigc::signal<void(const std::string &url)> signal_open_url;
    HistoryViewer(std::shared_ptr<gPanthera::LayoutManager> layout_manager, std::shared_ptr<HistoryManager> history_manager) : gPanthera::DockablePane(layout_manager, *Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0), "history", _("History"), Gtk::make_managed<Gtk::Image>(Gio::Icon::create("document-open-recent-symbolic"))), history_manager(std::move(history_manager)) {
        auto history_toolbar = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL, 0);
        auto history_button_previous = Gtk::make_managed<Gtk::Button>();
        history_button_previous->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-previous-symbolic")));
        history_button_previous->set_tooltip_text(_("Previous day"));
        auto history_button_next = Gtk::make_managed<Gtk::Button>();
        history_button_next->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-next-symbolic")));
        history_button_next->set_tooltip_text(_("Next day"));

        date_label = Gtk::make_managed<Gtk::Label>("");
        auto date_button = Gtk::make_managed<Gtk::MenuButton>();
        date_button->set_child(*date_label);
        date_button->set_tooltip_text(_("Select date"));
        date_button->set_direction(Gtk::ArrowType::NONE);
        auto date_popover = Gtk::make_managed<Gtk::Popover>();
        calendar = Gtk::make_managed<Gtk::Calendar>();
        date_popover->set_child(*calendar);
        date_button->set_popover(*date_popover);
        date_button->set_has_frame(false);
        date_button->set_hexpand(true);

        history_toolbar->append(*history_button_previous);
        history_toolbar->append(*date_button);
        history_toolbar->append(*history_button_next);
        auto box = dynamic_cast<Gtk::Box*>(this->child);
        box->append(*history_toolbar);

        history_button_next->signal_clicked().connect([this]() {
            Glib::DateTime calendar_day = calendar->get_date();
            Glib::DateTime datetime = Glib::DateTime::create_local(
                calendar_day.get_year(),
                calendar_day.get_month(),
                calendar_day.get_day_of_month(),
                0, 0, 0
            );
            auto next_entries = this->history_manager->storage.get_all<HistoryEntry>(
                sqlite_orm::where(sqlite_orm::c(&HistoryEntry::timestamp) >= datetime.to_unix() + 86400),
                sqlite_orm::order_by(&HistoryEntry::timestamp).asc()
            );
            if(next_entries.empty()) {
                return;
            }
            auto last_entry = next_entries.front();
            Glib::DateTime next_day = Glib::DateTime::create_now_local(last_entry.timestamp);
            Glib::DateTime new_date = Glib::DateTime::create_local(
                next_day.get_year(),
                next_day.get_month(),
                next_day.get_day_of_month(),
                0, 0, 0
            );
            calendar->select_day(new_date);
            reload_history();
        });

        history_button_previous->signal_clicked().connect([this]() {
            Glib::DateTime calendar_day = calendar->get_date();
            Glib::DateTime datetime = Glib::DateTime::create_local(
                calendar_day.get_year(),
                calendar_day.get_month(),
                calendar_day.get_day_of_month(),
                0, 0, 0
            );
            auto previous_entries = this->history_manager->storage.get_all<HistoryEntry>(
                sqlite_orm::where(sqlite_orm::c(&HistoryEntry::timestamp) < datetime.to_unix()),
                sqlite_orm::order_by(&HistoryEntry::timestamp).desc()
            );
            if(previous_entries.empty()) {
                return;
            }
            auto last_entry = previous_entries.front();
            Glib::DateTime previous_day = Glib::DateTime::create_now_local(last_entry.timestamp);
            Glib::DateTime new_date = Glib::DateTime::create_local(
                previous_day.get_year(),
                previous_day.get_month(),
                previous_day.get_day_of_month(),
                0, 0, 0
            );
            calendar->select_day(new_date);
            reload_history();
        });

        calendar->signal_day_selected().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history));
        calendar->signal_prev_month().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history));
        calendar->signal_next_month().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history));
        calendar->signal_prev_year().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history));
        calendar->signal_next_year().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history));
        Glib::DateTime datetime = Glib::DateTime::create_now_local();
        calendar->select_day(datetime);

        this->signal_pane_shown.connect([this]() {
            // Load the current date
            reload_history();
        });

        auto scrolled_window = Gtk::make_managed<Gtk::ScrolledWindow>();
        box_place = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0);
        auto viewport = Gtk::make_managed<Gtk::Viewport>(nullptr, nullptr);
        viewport->set_child(*box_place);
        scrolled_window->set_child(*viewport);
        scrolled_window->set_policy(Gtk::PolicyType::AUTOMATIC, Gtk::PolicyType::AUTOMATIC);
        scrolled_window->set_vexpand(true);
        scrolled_window->set_hexpand(true);
        box->append(*scrolled_window);

        // TODO: allow deleting entries
    }

    void reload_history() {
        Glib::DateTime calendar_day = calendar->get_date();
        Glib::DateTime datetime = Glib::DateTime::create_local(
            calendar_day.get_year(),
            calendar_day.get_month(),
            calendar_day.get_day_of_month(),
            0, 0, 0
        );
        date_label->set_text(datetime.format("%x"));
        auto box = Gtk::make_managed<Gtk::ListBox>();
        auto history_entries = history_manager->get_history_between(datetime.to_unix(), datetime.to_unix() + 86400);
        for(const auto &entry : history_entries) {
            auto row = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 4);
            auto title = Gtk::make_managed<Gtk::Label>(entry.title.empty() ? "Untitled" : entry.title);
            title->set_halign(Gtk::Align::START);
            title->set_ellipsize(Pango::EllipsizeMode::MIDDLE);
            auto label = Gtk::make_managed<Gtk::Label>(entry.url);
            label->set_halign(Gtk::Align::START);
            label->set_ellipsize(Pango::EllipsizeMode::MIDDLE);
            row->append(*title);
            row->append(*label);
            if(auto time = Glib::DateTime::create_now_local(entry.timestamp)) {
                label->set_tooltip_text(time.format("%c"));
                box->append(*row);
            }
        }
        if(box_place->get_first_child()) {
            box_place->remove(*box_place->get_first_child());
        }
        box->signal_row_activated().connect([this](Gtk::ListBoxRow *row) {
            if(auto box_row = dynamic_cast<Gtk::Box*>(row->get_child())) {
                if(auto label = dynamic_cast<Gtk::Label*>(box_row->get_last_child())) {
                    auto url = label->get_text();
                    if(!url.empty()) {
                        signal_open_url.emit(url);
                    }
                }
            }
        });
        box_place->append(*box);
    }
};

class PantheraWindow;

class PantheraWww : public Gtk::Application {
private:
    std::shared_ptr<gPanthera::ContentManager> content_manager;
    std::string cookie_file;
    std::vector<SearchEngine> search_engines;
    SearchEngine *default_search_engine;
    std::shared_ptr<HistoryManager> history_manager;
    Glib::RefPtr<Gio::Menu> main_menu;
    std::string new_tab_page;

    static void load_change_callback(WebKitWebView* object, WebKitLoadEvent load_event, gpointer data);
    static void notify_callback(GObject* object, GParamSpec* pspec, gpointer data);
    static void notify_focused_callback(GObject* object, GParamSpec* pspec, gpointer data);
    static void on_back_pressed(GtkGestureClick* gesture, int n_press, double x, double y, gpointer user_data);
    static void on_forward_pressed(GtkGestureClick* gesture, int n_press, double x, double y, gpointer user_data);
    static gboolean on_decide_policy(WebKitWebView* source, WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, gpointer user_data);

protected:
    void on_startup() override;
    void on_activate() override;
    void on_shutdown() override;
    PantheraWindow *make_window();

public:
    PantheraWww();
    ~PantheraWww();
    friend class PantheraWindow;
    void on_new_tab(gPanthera::ContentStack* stack, const Glib::ustring& url = "", bool focus = true, bool new_window = false);
    void set_search_engines_from_json(const std::string& json_string);
    static Glib::RefPtr<PantheraWww> create();
    std::shared_ptr<gPanthera::ContentManager> get_content_manager();
    void load_plugin(const std::string& plugin_path);
};

class PantheraWindow : public Gtk::ApplicationWindow {
private:
    std::shared_ptr<gPanthera::LayoutManager> layout_manager;
    Gtk::Entry *url_bar;
    HistoryViewer *history_viewer;
    gPanthera::ContentPage *controlled_page = nullptr;
public:
    friend class PantheraWww;
    explicit PantheraWindow(Gtk::Application *application) : Gtk::ApplicationWindow() {
        // There is a constructor with Glib::RefPtr<Gtk::Application>, but it is not appropriate
        // because the window will own the application, creating a cycle
        auto panthera = dynamic_cast<PantheraWww*>(application);
        if(!panthera) {
            throw std::runtime_error("Application is not a PantheraWww instance");
        }
        panthera->add_window(*this);
        this->set_default_size(800, 600);
        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");
        auto print_history_button = Gtk::make_managed<Gtk::Button>("Print history");
        print_history_button->signal_clicked().connect([this, panthera]() {
            auto history = panthera->history_manager->get_history();
            for(const auto &entry : history) {
                std::cout << "entry " << entry.id << ", url " << entry.url << ", unix time " << entry.timestamp << std::endl;
                // TODO: exclude redirecting URLs
            }
        });
        pane_1_content->append(*debug_button);
        pane_1_content->append(*print_history_button);
        auto pane_1_icon = Gtk::make_managed<Gtk::Image>(Gio::Icon::create("help-about-symbolic"));
        auto pane_1 = Gtk::make_managed<gPanthera::DockablePane>(layout_manager, *pane_1_content, "debug", _("Debugging options"), pane_1_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, 2, 1, 1);
        outer_grid->attach(*switcher_1, 1, 3, 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);
        panthera->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, panthera](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, panthera]() {
                panthera->on_new_tab(switcher->get_stack());
            });
            return new_tab_button;
        };
        auto content_stack = Gtk::make_managed<gPanthera::ContentStack>(panthera->content_manager, detach_handler);
        auto content_stack_switcher = Gtk::make_managed<gPanthera::ContentTabBar>(content_stack, Gtk::Orientation::HORIZONTAL, return_extra_child);
        panthera->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, 2, 1, 1);
        // 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, panthera]() {
            bool has_protocol = url_bar->get_text().find("://") != std::string::npos;
            if(!has_protocol) {
                url_bar->set_text("http://" + url_bar->get_text());
            }
            if(controlled_page) {
                if(auto webview = WEBKIT_WEB_VIEW(controlled_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);
        panthera->content_manager->signal_page_operated.connect([this, panthera](gPanthera::ContentPage *page) {
            if(!page->get_child()) {
                return;
            }
            if(!page->get_child()->get_first_child()) {
                return;
            }
            if(page->get_root() != this) {
                // The page is in some other window
                return;
            }
            controlled_page = page;
            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(panthera->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);
                    }
                }
            });
        });
        history_viewer = Gtk::make_managed<HistoryViewer>(layout_manager, panthera->history_manager);
        history_viewer->signal_open_url.connect([this, panthera](const std::string &url) {
            panthera->on_new_tab(nullptr, url, true);
        });
        // 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");

        auto back_action = Gio::SimpleAction::create("go_back");
        add_action(back_action);
        back_action->signal_activate().connect([this, panthera](const Glib::VariantBase&) {
            if(controlled_page) {
                if(auto webview = WEBKIT_WEB_VIEW(controlled_page->get_child()->get_first_child()->gobj())) {
                    webkit_web_view_go_back(webview);
                }
            }
        });
        back_button->set_action_name("win.go_back");

        auto forward_action = Gio::SimpleAction::create("go_forward");
        add_action(forward_action);
        forward_action->signal_activate().connect([this, panthera](const Glib::VariantBase&) {
            if(controlled_page) {
                if(auto webview = WEBKIT_WEB_VIEW(controlled_page->get_child()->get_first_child()->gobj())) {
                    webkit_web_view_go_forward(webview);
                }
            }
        });
        forward_button->set_action_name("win.go_forward");

        auto reload_action = Gio::SimpleAction::create("reload");
        add_action(reload_action);
        reload_action->signal_activate().connect([this, panthera](const Glib::VariantBase&) {
            if(controlled_page) {
                if(auto webview = WEBKIT_WEB_VIEW(controlled_page->get_child()->get_first_child()->gobj())) {
                    webkit_web_view_reload(webview);
                }
            }
        });
        reload_button->set_action_name("win.reload");

        // 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(panthera->search_engines.empty()) {
            search_bar->set_sensitive(false);
            search_bar->set_placeholder_text(_("No search"));
        }
        auto search_callback = [this, search_bar, content_stack, panthera]() {
            // Create a new tab with the search results
            if(panthera->content_manager->get_last_operated_page()) {
                panthera->on_new_tab(nullptr);
            } else {
                panthera->on_new_tab(content_stack);
            }
            auto page = panthera->content_manager->get_last_operated_page();
            if(page) {
                if(auto webview = WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())) {
                    auto search_url = panthera->default_search_engine->get_search_url(search_bar->get_text());
                    webkit_web_view_load_uri(webview, search_url.c_str());
                }
            }
        };
        if(panthera->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(panthera->default_search_engine) {
            auto search_button = Gtk::make_managed<Gtk::Button>(panthera->default_search_engine->name);
            search_button->signal_clicked().connect(search_callback);
            main_toolbar->append(*search_button);
        }
        outer_grid->attach(*main_toolbar, 0, 1, 2, 1);
        this->set_child(*outer_grid);
        debug_button->signal_clicked().connect([this, panthera]() {
            if(panthera->content_manager->get_last_operated_page()) {
                std::cout << "Last operated page: " << panthera->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(*history_viewer);

            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, panthera](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;
        });
        set_show_menubar(true);
    }
    ~PantheraWindow() override = default;
};

void PantheraWww::load_change_callback(WebKitWebView *object, WebKitLoadEvent load_event, gpointer data) {
    if(auto self = static_cast<PantheraWww*>(data)) {
        if(load_event == WEBKIT_LOAD_COMMITTED) {
            if(webkit_web_view_get_title(WEBKIT_WEB_VIEW(object)) == nullptr) {
                self->history_manager->log_url(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(object)), "");
            } else {
                self->history_manager->log_url(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(object)),
                                               webkit_web_view_get_title(WEBKIT_WEB_VIEW(object)));
            }
            // TODO: reload visible history viewers
        }
    }
}

void PantheraWww::notify_callback(GObject *object, GParamSpec *pspec, gpointer data) {
    if(!gtk_widget_get_parent(GTK_WIDGET(object))) {
        return;
    }
    if(auto self = 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, "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))) {
                        gtk_image_set_from_paintable(image->gobj(), GDK_PAINTABLE(favicon));
                    }
                }
            }
        }
    }
}

void PantheraWww::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) {
            if(auto main_window = dynamic_cast<PantheraWindow*>(page->get_root())) {
                main_window->url_bar->set_text(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(object)));
            }
        }
    }
}

void PantheraWww::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);
}

void PantheraWww::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);
}

gboolean PantheraWww::on_decide_policy(WebKitWebView *source, WebKitPolicyDecision *decision, WebKitPolicyDecisionType type, gpointer user_data) {
    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));
            Glib::ustring url = Glib::ustring(webkit_uri_request_get_uri(webkit_navigation_action_get_request(action)));
            if(!starts_with(url, "about:") && url.find("://") == Glib::ustring::npos) {
                // It is a special scheme (mailto:, tel: etc.)
                try {
                    Gio::AppInfo::launch_default_for_uri(url);
                } catch(const Glib::Error &exception) {
                    std::cerr << "Failed to launch special URI: " << exception.what() << std::endl;
                }
                webkit_policy_decision_ignore(decision);
                return true;
            }
            if(webkit_navigation_action_get_mouse_button(action) == 2) {
                // Middle-click opens in a new window
                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 PantheraWww::on_new_tab(gPanthera::ContentStack *stack, const Glib::ustring &url, bool focus, bool new_window) {
    if(!stack) {
        // Find the current area
        stack = content_manager->get_last_operated_page()->get_stack();
    }
    Glib::ustring url_ = url;
    if(url.empty()) {
        url_ = new_tab_page;
    }

    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), this);
    g_signal_connect(webview, "load-changed", G_CALLBACK(load_change_callback), this);
    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);
    }
}

PantheraWindow *PantheraWww::make_window() {
    auto window = Gtk::make_managed<PantheraWindow>(this);
    return window;
}

void PantheraWww::on_startup() {
    bindtextdomain("panthera-www", "./locales");
    textdomain("panthera-www");
    Gtk::Application::on_startup();
    // 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);
    }

    // Load settings
    new_tab_page = "about:blank";
    std::ifstream settings_file_in("settings.json");
    if(settings_file_in) {
        std::string settings_json((std::istreambuf_iterator<char>(settings_file_in)), std::istreambuf_iterator<char>());
        settings_file_in.close();
        auto json = nlohmann::json::parse(settings_json);
        if(json.contains("ntp")) {
            new_tab_page = json["ntp"].get<std::string>();
        }
    } else {
        settings_file_in.close();
        auto empty_json = nlohmann::json::object();
        empty_json["ntp"] = "about:blank";
        std::ofstream settings_file_out("settings.json");
        settings_file_out << empty_json.dump(4);
        settings_file_out.close();
    }

    // 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();
    }
    history_manager = std::make_shared<HistoryManager>("history.db");

    // Known bug <https://gitlab.gnome.org/GNOME/epiphany/-/issues/2714>:
    // JS can't veto the application's accelerators using `preventDefault()`. This is
    // not possible in WebKitGTK, or at least I can't find a way to do it.

    main_menu = Gio::Menu::create();
    // File
    auto file_menu = Gio::Menu::create();
    // New tab
    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"});
    file_menu->append(_("New _Tab"), "app.new_tab");
    // Close tab
    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"});
    file_menu->append(_("_Close Tab"), "app.close_tab");
    // New window
    auto new_window_action = Gio::SimpleAction::create("new_window");
    new_window_action->signal_activate().connect([this](const Glib::VariantBase&) {
        on_activate();
    });
    add_action(new_window_action);
    set_accels_for_action("app.new_window", {"<Primary>N"});
    file_menu->append(_("_New Window"), "app.new_window");
    // Quit
    auto quit_action = Gio::SimpleAction::create("quit");
    quit_action->signal_activate().connect([this](const Glib::VariantBase&) {
        quit();
    });
    add_action(quit_action);
    set_accels_for_action("app.quit", {"<Primary>Q"});
    file_menu->append(_("_Quit"), "app.quit");

    main_menu->append_submenu(_("_File"), file_menu);

    // Go
    auto go_menu = Gio::Menu::create();
    // Back
    set_accels_for_action("win.go_back", {"<Alt>Left"});
    go_menu->append(_("_Back"), "win.go_back");
    // Forward
    set_accels_for_action("win.go_forward", {"<Alt>Right"});
    go_menu->append(_("_Forward"), "win.go_forward");

    main_menu->append_submenu(_("_Go"), go_menu);

    // View
    auto view_menu = Gio::Menu::create();
    // Reload
    set_accels_for_action("win.reload", {"F5", "<Primary>R"});
    view_menu->append(_("_Reload"), "win.reload");

    main_menu->append_submenu(_("_View"), view_menu);

    set_menubar(main_menu);
}

void PantheraWww::on_activate() {
    auto window = make_window();
    window->present();
}

void PantheraWww::on_shutdown() {
    Gtk::Application::on_shutdown();
}

void PantheraWww::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;
        }
    }
}

PantheraWww::PantheraWww() : Gtk::Application("com.roundabout_host.roundabout.PantheraWww", Gio::Application::Flags::NONE) {
}

Glib::RefPtr<PantheraWww> PantheraWww::create() {
    return Glib::make_refptr_for_instance<PantheraWww>(new PantheraWww());
}

void PantheraWww::load_plugin(const std::string &plugin_path) {
    // TODO: needs to be reworked, to work with multi-window
    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();
}

PantheraWww::~PantheraWww() = default;

/*
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);
        // TODO: Port to multi-window
        //app->get_layout_manager()->add_pane(new_pane);
    }
}
*/

int main(int argc, char *argv[]) {
    gPanthera::init();

    auto app = PantheraWww::create();

    return app->run(argc, argv);
}
