#include "GuiApplication.h"

#include "Widget.h"
#include "UiInterfaceFactory.h"
#include "Window.h"
#include "TextElement.h"
#include "WindowManager.h"
#include "TextEditorView.h"
#include "AudioEditorView.h"
#include "ImageEditorView.h"
#include "WebClientView.h"
#include "TabbedPanelWidget.h"
#include "TopBar.h"
#include "StatusBar.h"
#include "HorizontalSpacer.h"
#include "FileLogger.h"

GuiApplication::GuiApplication()
    : AbstractDesktopApp(),
      mMainApplication(),
      mDesktopManager(DesktopManager::Create())
{

}

GuiApplication::~GuiApplication()
{

}

void GuiApplication::SetMainApplication(MainApplicationPtr app)
{
    mMainApplication = app;
    mDesktopManager->SetMainApp(app);
}

void GuiApplication::SetUpWidget()
{
    auto mainWindow = mDesktopManager->GetWindowManager()->GetMainWindow();
    mainWindow->SetSize(800, 600);

    auto tabbedPanel = TabbedPanelWidget::Create();

    auto textEditor = TextEditorView::Create();
    auto path = mMainApplication->GetCommandLineArgs()->getLaunchPath();
    path /= "out.txt";
    textEditor->GetController()->SetSavePath(path);
    textEditor->GetController()->SetLoadPath(path);
    textEditor->Initialize();
    tabbedPanel->AddPanel(std::move(textEditor), "Text Editor");

    auto audioEditor = AudioEditorView::Create();
    tabbedPanel->AddPanel(std::move(audioEditor), "Audio Editor");

    auto imageEditor = ImageEditorView::Create();
    tabbedPanel->AddPanel(std::move(imageEditor), "Image Editor");

    auto webClient = WebClientView::Create();
    tabbedPanel->AddPanel(std::move(webClient), "Web Client");

    auto topBar = TopBar::Create();
    auto statusBar = StatusBar::Create();

    auto horizontalSpace = HorizontalSpacer::Create();
    horizontalSpace->AddWidgetWithScale(std::move(topBar), 1);
    horizontalSpace->AddWidgetWithScale(std::move(tabbedPanel), 20);
    horizontalSpace->AddWidgetWithScale(std::move(statusBar), 1);

    mainWindow->AddWidget(std::move(horizontalSpace));
}

void GuiApplication::Run()
{
    auto mainWindow = mDesktopManager->GetWindowManager()->GetMainWindow();
    SetUpWidget();

    MLOG_INFO("Creating Window Interface");
    auto window_interface = UiInterfaceFactory::create(mDesktopManager.get());

    window_interface->initialize();
    window_interface->addWindow(mainWindow);
    window_interface->showWindow(mainWindow);
    window_interface->loop();

    window_interface->shutDown();

    MLOG_INFO("Window Interface Shut Down");
}
