#include <Display/WidgetDisplay/LoginDisplay/LoginDisplay.hpp>
#include <Widget/Label/Label.hpp>
#include <Widget/Layout/Center/Center.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/Button/Button.hpp>
#include <Display/WidgetDisplay/ServerSelection/ServerSelection.hpp>
#include <Widget/TextField/TextField.hpp>
#include <Display/WidgetDisplay/WorldDisplay/WorldDisplay.hpp>
#include <Display/WidgetDisplay/MessageDisplay/MessageDisplay.hpp>
#include <Utilities/ServerSessionTable.hpp>
#include <World/RemoteWorld/RemoteWorld.hpp>
#include <Display/WidgetDisplay/ConnectingDisplay/ConnectingDisplay.hpp>
#include <Authenticator/PasswordAuthenticator/PasswordAuthenticator.hpp>
#include <Widget/Panel/Panel.hpp>
#include <Widget/Layout/Row/Row.hpp>
#include <Widget/Layout/Column/HorizontalSeparator/HorizontalSeparator.hpp>
#include <Widget/Button/BackButton/BackButton.hpp>
#include <Widget/Layout/CompoundWidget/Form/Form.hpp>

bool LoginDisplay::canLogIn()
{
    return server.size() != 0 && userName.size() != 0 && password.size() != 0;
}

void LoginDisplay::onLogin()
{
    if (canLogIn())
    {
        UserDB::SessionID sid{};
        setServerSession(server, userName, sid);

        std::shared_ptr<PasswordAuthenticator> auth = std::make_shared<PasswordAuthenticator>(userName, password);
        Display::setCurrent<ConnectingDisplay>(auth, server);
    }
}

LoginDisplay::LoginDisplay(std::string message, std::string server, std::string userName) :
    server(server),
    userName(userName)
{
    setWidget(
        new Center(
            new Form(
                "Login",
                new Column(
                    new Label(message),
                    new Panel(glm::ivec2(100, 2)),

                    new Label("Server:"),
                    new TextField(this->server, [this]() { onLogin(); }),
                    new Panel(glm::ivec2(0, 2)),
                    new Label("User name:"),
                    new TextField(this->userName, [this]() { onLogin(); }),
                    new Panel(glm::ivec2(0, 2)),
                    new Label("Password:"),
                    new TextField(this->password, [this]() { onLogin(); }, true)
                ),

                Layout::WithProportion<1>(),
                (new Button("Log in", [this]() { onLogin(); }))->enabledIf([this]() { return canLogIn(); }),
                Layout::WithProportion<1>(),
                new BackButton("Cancel")
            )
        )
    );
}