//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Overlay/EllipseOverlay.cpp
//! @brief     Implements class EllipseOverlay.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Overlay/EllipseOverlay.h"
#include "GUI/Model/Mask/MaskItems.h"
#include "GUI/View/Plotter/ColorMap.h"

EllipseOverlay::EllipseOverlay(EllipseItem* item, ColorMap* plot)
    : IRectangularOverlay(plot)
    , m_item(item)
{
    m_item->maskVisibilityChanged();
}

OverlayItem* EllipseOverlay::parameterizedItem() const
{
    return m_item;
}

void EllipseOverlay::onChangedX()
{
    setBlockOnProperty(true);
    m_item->setXCenter(x2coo(this->x()));
    setBlockOnProperty(false);
}

void EllipseOverlay::onChangedY()
{
    setBlockOnProperty(true);
    m_item->setYCenter(y2coo(this->y()));
    setBlockOnProperty(false);
}

void EllipseOverlay::onPropertyChange()
{
    update_view();
    setX(x2pix(m_item->xCenter().dVal()));
    setY(y2pix(m_item->yCenter().dVal()));
    setTransform(QTransform().rotate(-1.0 * m_item->angle().dVal()));
}

QPainterPath EllipseOverlay::shape() const
{
    QPainterPath path;
    path.addEllipse(m_mask_rect);
    return path;
}

void EllipseOverlay::resizeX(double xl, double xh)
{
    m_item->setXCenter(x2coo((xl + xh) / 2));
    m_item->setXRadius((x2coo(xh) - x2coo(xl)) / 2);
}

void EllipseOverlay::resizeY(double yl, double yh)
{
    m_item->setYCenter(y2coo((yl + yh) / 2));
    m_item->setYRadius((y2coo(yl) - y2coo(yh)) / 2);
}

//! updates position of view using item properties

void EllipseOverlay::updatePosition()
{
    setX(x2pix(m_item->xCenter().dVal()));
    setY(y2pix(m_item->yCenter().dVal()));

    if (m_item->angle().dVal() != 0)
        setTransform(QTransform().rotate(-1 * m_item->angle().dVal()));
}

QRectF EllipseOverlay::maskRectangle()
{
    return QRectF(-width() / 2, -height() / 2, width(), height());
}

qreal EllipseOverlay::width() const
{
    return x2pix(m_item->xCenter().dVal() + m_item->xRadius().dVal())
           - x2pix(m_item->xCenter().dVal() - m_item->xRadius().dVal());
}

qreal EllipseOverlay::height() const
{
    return y2pix(m_item->yCenter().dVal() - m_item->yRadius().dVal())
           - y2pix(m_item->yCenter().dVal() + m_item->yRadius().dVal());
}
