#!/usr/bin/env python

# This was borrowed (and adapted) from the Taurus project
#
# http://taurus-scada.org
#
# Copyright 2017 CELLS / ALBA Synchrotron, Bellaterra, Spain
#
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Taurus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Taurus.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import

__all__ = ["Y2ViewBox"]


from pyqtgraph import ViewBox

from .configuration import BaseConfigurableClass


class Y2ViewBox(ViewBox, BaseConfigurableClass):
    """
    Y2ViewBox provides a secondary axis to a pyqtgraph.PlotItem.
    It was adapted from the Y2ViewBox class of the taurus.qt.qtgui.tpg module
    (see http://taurus-scada.org )
    """

    def __init__(self, *args, **kwargs):
        BaseConfigurableClass.__init__(self)
        ViewBox.__init__(self, *args, **kwargs)

        self.registerConfigProperty(self._getState, self.setState, "viewState")
        self._isAttached = False
        self.plotItem = None

    def attachToPlotItem(self, plot_item):
        if self._isAttached:
            return  # TODO: log a message it's already attached
        self._isAttached = True

        mainViewBox = plot_item.getViewBox()
        mainViewBox.sigResized.connect(self.updateViews)

        self.plotItem = plot_item

    def updateViews(self, viewBox):
        self.setGeometry(viewBox.sceneBoundingRect())
        self.linkedViewChanged(viewBox, self.XAxis)

    def removeItem(self, item):
        ViewBox.removeItem(self, item)
        # when last curve is removed from self (axis Y2), we must remove the
        # axis from scene and hide the axis.
        if len(self.addedItems) < 1:
            self.plotItem.scene().removeItem(self)
            self.plotItem.hideAxis("right")

    def addItem(self, item, ignoreBounds=False):
        ViewBox.addItem(self, item, ignoreBounds=ignoreBounds)

        if len(self.addedItems) == 1:
            # when the first curve is added to self (axis Y2), we must
            # add Y2 to main scene(), show the axis and link X axis to self.
            self.plotItem.showAxis("right")
            self.plotItem.scene().addItem(self)
            self.plotItem.getAxis("right").linkToView(self)
            self.setXLink(self.plotItem)

    def _getState(self):
        """Same as ViewBox.getState but removing viewRange conf to force
        a refresh with targetRange when loading
        """
        state = self.getState(copy=True)
        del state["viewRange"]
        return state
