#include "HorizontalSpacer.h"
#include "TextEditorView.h"
#include "VerticalSpacer.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->SetBackgroundColor(Color::Create(181, 189, 200));
    label->SetMargin(1);

    auto textBox = TextBox::Create();
    mTextBox = textBox.get();

    auto saveButton = Button::Create();
    saveButton->SetLabel("Save");
    saveButton->SetBackgroundColor(Color::Create(200, 200, 200));
    saveButton->SetMargin(2);
    auto onSave = [this](Widget* self){
                if(this && mController && mTextBox)
                {
                    mController->SetContent(mTextBox->GetContent());
                    mController->OnSave();
                };
            };
    saveButton->SetOnClickFunction(onSave);

    auto clearButton = Button::Create();
    clearButton->SetLabel("Clear");
    clearButton->SetBackgroundColor(Color::Create(200, 200, 200));
    clearButton->SetMargin(2);
    auto onClear = [this](Widget* self){
                if(this && mController && mTextBox)
                {
                    mController->OnClear();
                    mTextBox->SetContent("");
                };
            };
    clearButton->SetOnClickFunction(onClear);

    auto loadButton = Button::Create();
    loadButton->SetLabel("Load");
    loadButton->SetBackgroundColor(Color::Create(200, 200, 200));
    loadButton->SetMargin(2);
    auto onLoad = [this](Widget* self){
                if(this && 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>();
}
