#include "CanvasView.h"

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

#include "CanvasController.h"
#include "CanvasDrawingArea.h"
#include "CanvasCommandSelectorView.h"

#include "Theme.h"
#include "TextNode.h"
#include "GeometryNode.h"

#include "Label.h"
#include "Button.h"

CanvasView::CanvasView()
      : mController(CanvasController::Create())
{
    initialize();
}

CanvasView::~CanvasView()
{

}

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

void CanvasView::initialize()
{
    auto label = Label::Create();
    label->setLabel("Canvas");
    label->setBackgroundColor(Theme::getBannerBackground());
    label->setMargin(1);

    auto controls = std::make_unique<CanvasCommandSelectorView>();
    controls->setBackgroundColor(Theme::getBannerBackground());
    controls->setMargin(1);

    auto on_draw_command_changed = [this](CanvasDrawCommand command){
        onDrawCommandChanged(command);
    };
    controls->setCommandSelectedCallback(on_draw_command_changed);

    auto drawing_area = std::make_unique<CanvasDrawingArea>();
    drawing_area->setBackgroundColor(Theme::getBackgroundPrimary());
    drawing_area->setMargin(1);
    mDrawingArea = drawing_area.get();

    auto control_draw_vspacer = VerticalSpacer::Create();
    control_draw_vspacer->addWidgetWithScale(std::move(controls), 1);
    control_draw_vspacer->addWidgetWithScale(std::move(drawing_area), 10);

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

    hSpacer->addWidgetWithScale(std::move(control_draw_vspacer), 10);

    auto cache_button_spacer = initializeCacheButtons();
    hSpacer->addWidgetWithScale(std::move(cache_button_spacer), 1);

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

void CanvasView::onDrawCommandChanged(CanvasDrawCommand command)
{
    mDrawingArea->setActiveDrawingCommand(command);
}

std::unique_ptr<Widget> CanvasView::initializeCacheButtons()
{
    auto saveButton = Button::Create();
    saveButton->setLabel("Save");
    saveButton->setBackgroundColor(Theme::getButtonPrimaryBackground());
    saveButton->setMargin(2);

    auto clearButton = Button::Create();
    clearButton->setLabel("Clear");
    clearButton->setBackgroundColor(Theme::getButtonPrimaryBackground());
    clearButton->setMargin(2);

    auto loadButton = Button::Create();
    loadButton->setLabel("Load");
    loadButton->setBackgroundColor(Theme::getButtonPrimaryBackground());
    loadButton->setMargin(2);

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

