#include "CLineItem.h"

#include <QPen>

CLineItem::CLineItem(QGraphicsItem *parent) : CLineItem(QPointF(), QPointF(), parent) { }

CLineItem::CLineItem(const QPointF &startPos, const QPointF &endPos, QGraphicsItem *parent)
    : CPathItem(parent), m_startPos(startPos), m_endPos(endPos)
{
    updatePath();
}

QPointF CLineItem::startPos() const
{
    return m_startPos;
}

void CLineItem::setStartPos(const QPointF start)
{
    m_startPos = start;
    updatePath();
}

QPointF CLineItem::endPos() const
{
    return m_endPos;
}

void CLineItem::setEndPos(const QPointF end)
{
    m_endPos = end;
    updatePath();
}

CLineItem::CLineType CLineItem::lineType() const
{
    return m_lineType;
}

void CLineItem::setLineType(CLineItem::CLineType type)
{
    m_lineType = type;
    updatePath();
}

bool CLineItem::showArrow() const
{
    return m_showArrow;
}

void CLineItem::setShowArrow(bool s)
{
    m_showArrow = s;
}

void CLineItem::updatePath()
{
    QPainterPath path;
    switch (m_lineType) {
    case Curve: {
        path.moveTo(m_startPos);
        double d     = (m_endPos.x() - m_startPos.x()) / 4;
        QPointF ctr1 = QPointF(m_startPos.x() + d, m_startPos.y());
        QPointF ctr2 = QPointF(m_endPos.x() - d, m_endPos.y());
        path.cubicTo(ctr1, ctr2, m_endPos);
        break;
    }
    case Line: {
        path.moveTo(m_startPos);
        path.lineTo(m_endPos);
        break;
    }
    case Polyline: {
        path.moveTo(m_startPos);
        path.lineTo(QPointF(m_startPos.x() + 20, m_startPos.y()));
        path.lineTo(QPointF(m_startPos.x() + 20, m_endPos.y()));
        path.lineTo(m_endPos);
        break;
    }
    case CurveToLine: {
        path.moveTo(m_startPos);
        double d     = 5;
        QPointF ctr1 = QPointF(m_startPos.x() + d, m_startPos.y());
        QPointF ctr2 = QPointF(m_startPos.x() + d * 2, m_endPos.y());
        QPointF p    = QPointF(m_startPos.x() + d * 3, m_endPos.y());
        path.cubicTo(ctr1, ctr2, p);
        path.lineTo(m_endPos);
        break;
    }
    }

    if (m_showArrow && m_startPos != m_endPos) {
        path.moveTo(m_endPos + QPointF(-10, -5));
        path.lineTo(m_endPos);
        path.lineTo(m_endPos + QPointF(-10, 5));
    }

    setPath(path);
}