#include "EEDB.hpp"

#include <Wt/WApplication>
#include <Wt/WEnvironment>

#include <eedb/Session.hpp>
#include <eedb/auth/PgUserAuth.hpp>
#include <eedb/db/connection.hpp>
#include <eedb/widgets/AuthPage.hpp>
#include <eedb/widgets/HomePage.hpp>
#include <eedb/widgets/Theme.hpp>

#include <memory>

#include <Wt/WApplication>
#include <Wt/WBorderLayout>
#include <Wt/WContainerWidget>
#include <Wt/WEnvironment>
#include <Wt/WLineEdit>
#include <Wt/WMessageBox>
#include <Wt/WNavigationBar>
#include <Wt/WPopupMenu>
#include <Wt/WServer>
#include <Wt/WStackedWidget>
#include <Wt/WText>
#include <Wt/WTextArea>

#include <eedb/widgets/BootstrapTheme.hpp>
using std::move;

namespace eedb {

EEDB::EEDB(std::unique_ptr< Session > session, AuthPageFactory authPageFactory, HomePageFactory homePageFactory)
 : Wt::WApplication(session->enviroment()),
   _session(move(session)),
   _theme(std::make_unique< eedb::BootstrapTheme >()),
   _authPageFactory(move(authPageFactory)),
   _authPage(nullptr),
   _homePageFactory(move(homePageFactory)),
   _homePage(nullptr) //
{
    root()->addStyleClass("container");
    useStyleSheet("/resources/style.css");

    setTheme(_theme->create(this));

    _authPage = _authPageFactory();
    _authPage->registerNeedVerification([] {});
    _authPage->registerOnUserWeakLogin([=] { authEventLogin(LoginState::weak); });
    _authPage->registerOnUserStrongLogin([=] { authEventLogin(LoginState::strong); });
    _authPage->registerOnUserLogout([=] { authEventLogout(); });
    _authPage->attachTo(root());
    _authPage->processEnvironment();
}

void EEDB::authEventLogin(EEDB::LoginState state) {
    using namespace Wt;

    root()->removeStyleClass("container");
    _authPage->detach();
    _homePage = _homePageFactory();
    _homePage->attachTo(root());

    Wt::log("notice") << "Clearing root and creating widgets";
    //        //        new eedb::Home(container, &_authWidget->login());
}

void EEDB::authEventLogout() {
    Wt::log("notice") << "User logged out.";
    redirect(url());
    quit();
}
}
