#include "wgt_listitem.h"
#include <QHBoxLayout>
#include <QApplication>
#include <QCloseEvent>
#include <QDrag>
#include <QMimeData>
#include "states.h"
namespace {

}

//region ListItemWidget
//= public
ListItemWidget::ListItemWidget(QWidget *inner, QWidget *parent, SelectedItemWidgetGroup *group)
: QWidget(parent), m_group(group), m_inner(inner) {
    m_inner->setParent(this);
    setAttribute(Qt::WA_StyledBackground, true);
    auto *layout = new QHBoxLayout(this);
    layout->setContentsMargins(4, 4, 4, 4);
    layout->addWidget(inner);

    setAutoFillBackground(true);
    SetSelected(false);
    if (group) group->Add(this);
}
ListItemWidget::~ListItemWidget() {
    if (m_group) m_group->Remove(this);
}
void ListItemWidget::SetMime(const char *mimeType, const char *mimeData) {
    m_MimeType = mimeType;
    m_mimeData = mimeData;
}
std::string ListItemWidget::GetMimeData() {
    return m_mimeData;
}

void ListItemWidget::SetSelected(bool selected) {
    if (m_group) {
        if (!m_selected && selected) {
            m_group->Select(this);
        }
    } else {
        SetSelectedFromGroup_(selected);
    }
}
bool ListItemWidget::IsSelected() const {
    return m_selected;
}

//= protected
void ListItemWidget::mousePressEvent(QMouseEvent *e) {
    if (e->button() != Qt::MouseButton::LeftButton) return;
    m_prepareClick = true;
    m_pressPos = e->pos();
}
void ListItemWidget::mouseMoveEvent(QMouseEvent *e) {
    if (!(e->buttons() & Qt::LeftButton)) {
        return;
    }
    int distance = (e->position().toPoint() - m_pressPos).manhattanLength();
    if (distance >= QApplication::startDragDistance()) {
        m_prepareClick = false;
        TryStartDrag();
    }
}
void ListItemWidget::mouseReleaseEvent(QMouseEvent *event) {
    if (event->button() != Qt::MouseButton::LeftButton) return;
    if (m_prepareClick) {
        emit Clicked(this);
    }
}
void ListItemWidget::TryStartDrag() {}

//=private
void ListItemWidget::SetSelectedFromGroup_(bool selected) {
    m_selected = selected;
    if (selected) {
        setStyleSheet("background-color: #3a75c4;");
    } else {
        setStyleSheet("background-color: transparent;");
    }
}


//endregion


//region DragItemWidget
//= public
DragItemWidget::DragItemWidget(QWidget *inner, QWidget *parent, SelectedItemWidgetGroup *group)
: ListItemWidget(inner, parent, group) {}

void DragItemWidget::TryStartDrag() {
    if (m_dragging) return;
    m_dragging = true;
    auto *drag = new QDrag{this};
    auto *mime = new QMimeData{};

    QByteArray arr{m_mimeData.data(), static_cast<int>(m_mimeData.size())};
    mime->setData(m_MimeType, arr);

    drag->setMimeData(mime);
    Qt::DropAction result = drag->exec(Qt::MoveAction);
    (void)result;

    m_dragging = false;
}






//endregion














//
