#include <eedb/widgets/DefaultHomePage.hpp>

#include <Wt/Auth/Login>
#include <Wt/WContainerWidget>
#include <Wt/WEnvironment>
#include <Wt/WLineEdit>
#include <Wt/WMessageBox>
#include <Wt/WServer>
#include <Wt/WStackedWidget>
#include <Wt/WText>
#include <Wt/WTextArea>

#include <Wt/WIconPair>
#include <Wt/WLogger>
#include <Wt/WText>
#include <Wt/WTreeNode>
#include <Wt/WTreeView>

#include <Wt/WHBoxLayout>
#include <Wt/WVBoxLayout>

#include <eedb/Session.hpp>
#include <eedb/data/CategoriesModel.hpp>
#include <eedb/widgets/NavigationBar.hpp>

namespace eedb {

auto make_tree() {
    auto tree = new Wt::WTreeView();

    Wt::WAbstractItemModel * model = new eedb::CategoriesModel(tree);
    tree->setModel(model);

    tree->setColumnResizeEnabled(true);
    tree->setSortingEnabled(false);
    tree->setSelectionMode(Wt::SingleSelection);
    tree->setEditTriggers(Wt::WAbstractItemView::NoEditTrigger);

    return tree;
}

eedb::DefaultHomePage::DefaultHomePage(Session & session, std::unique_ptr< eedb::NavigationBar > navigationBar)
 : _session(session), _navigationBar(std::move(navigationBar)) {}

DefaultHomePage::~DefaultHomePage() = default;

void DefaultHomePage::attachTo(Wt::WContainerWidget * container) {
    auto stackedWidget = new Wt::WStackedWidget();

    _navigationBar->attachTo(stackedWidget);
    _navigationBar->registerLogoutAction([=]() { this->_session.login().logout(); });

    Wt::WVBoxLayout * vbox = new Wt::WVBoxLayout();
    container->setLayout(vbox);
    vbox->addWidget(stackedWidget, 0);

    Wt::WHBoxLayout * hbox = new Wt::WHBoxLayout();
    vbox->addLayout(hbox, 10);

    Wt::WStackedWidget * contents = new Wt::WStackedWidget();

    _categoryTree = make_tree();
    _categoryTree->clicked().connect([=](auto...) { Wt::log("notice") << "Item selection changed"; });

    hbox->addWidget(_categoryTree, 1);
    hbox->addWidget(contents, 2);
    hbox->setResizable(0, true);
}
}
