#include "TextEditorView.h"

#include "HorizontalSpacer.h"
#include "VerticalSpacer.h"

#include "Theme.h"

#include "TextNode.h"

#include <iostream>

TextEditorView::TextEditorView()
    : mTextBox(),
      mController(TextEditorController::Create())
{

}

TextEditorController* TextEditorView::getController()
{
    return mController.get();
}

void TextEditorView::initialize()
{
    auto label = Label::Create();
    label->setLabel("Text Editor");
    label->setMargin(1);

    auto textBox = TextBox::Create();
    textBox->setName("Text Box");
    mTextBox = textBox.get();

    auto saveButton = Button::Create();
    saveButton->setLabel("Save");
    saveButton->setBackground(Theme::Sys::Color::Primary);
    saveButton->setMargin(2);
    auto onSave = [this](Widget*){
                if(mController && mTextBox)
                {
                    mController->SetContent(mTextBox->getContent());
                    mController->OnSave();
                };
            };
    saveButton->setOnClickFunction(onSave);

    auto clearButton = Button::Create();
    clearButton->setLabel("Clear");
    clearButton->setMargin(2);
    auto onClear = [this](Widget*){
                if(mController && mTextBox)
                {
                    mController->OnClear();
                    mTextBox->setContent("");
                };
            };
    clearButton->setOnClickFunction(onClear);

    auto loadButton = Button::Create();
    loadButton->setLabel("Load");
    loadButton->setMargin(2);
    auto onLoad = [this](Widget*){
                if(mController && mTextBox)
                {
                    mController->OnLoad();
                    mTextBox->setContent(mController->GetContent());
                };
            };
    loadButton->setOnClickFunction(onLoad);

    auto buttonSpacer = VerticalSpacer::Create();
    buttonSpacer->addWidgetWithScale(std::move(saveButton), 1);
    buttonSpacer->addWidgetWithScale(std::move(clearButton), 1);
    buttonSpacer->addWidgetWithScale(std::move(loadButton), 1);

    auto hSpacer = HorizontalSpacer::Create();
    hSpacer->addWidgetWithScale(std::move(label), 1);
    hSpacer->addWidgetWithScale(std::move(textBox), 14);
    hSpacer->addWidgetWithScale(std::move(buttonSpacer), 1);

    addWidget(std::move(hSpacer));
}

std::unique_ptr<TextEditorView> TextEditorView::Create()
{
    return std::make_unique<TextEditorView>();
}
