#pragma once

#include <Zeichnung.h>

#include "DragElement.h"

template<typename Source, typename Element> class DragController
    : public Framework::ReferenceCounter
{
private:
    Source* container;
    Element currentElement;
    DragElement* drag;
    std::function<void()> onDragEnd;

public:
    DragController()
        : ReferenceCounter()
    {
        container = 0;
        currentElement = 0;
        drag = new DragElement();
    }

    ~DragController()
    {
        if (this->container) stopDrag();
        drag->release();
    }

    void beginDrag(Source* container,
        Element element,
        Framework::Bild* zDragDisplay,
        std::function<void()> onDragEnd)
    {
        if (this->container) stopDrag();
        ((BildZ*)drag)->setBildZ(dynamic_cast<Bild*>(zDragDisplay->getThis()));
        window->zBildschirm()->addMember(
            dynamic_cast<Zeichnung*>(drag->getThis()));
        this->container = container;
        this->currentElement = element;
        this->onDragEnd = onDragEnd;
    }

    Source* getCurrentDragContainer() const
    {
        return container;
    }

    Element getCurrentDaragElement() const
    {
        return currentElement;
    }

    void stopDrag()
    {
        if (container)
        {
            window->zBildschirm()->removeMember(drag);
            onDragEnd();
            container = 0;
            currentElement = 0;
        }
    }
};