# encoding=utf-8

__author__ = "Aaron Randreth"
__copyright__ = "Copyright 2015+, Consortium MonPaGe"
__license__ = "Creative Commons 4.0 By-Nc-Sa"
__maintainer__ = "Roland Trouville"
__email__ = "contact.monpage@gmail.com"
__status__ = "Production"

import pyqtgraph as pg  # type: ignore
# pg.setConfigOptions(foreground="k", background="d")


class DoubleAxisPlotItem(pg.PlotItem):
	second_axis_color: str
	second_axis_width: int

	right: pg.ViewBox
	right_visible: bool
	left: pg.ViewBox

	def __init__(self, second_axis_color: str = "r", second_axis_width: int = 3):
		super().__init__()

		self.right = pg.ViewBox()
		self.left = self.vb
		self.second_axis_color = second_axis_color
		self.second_axis_width = second_axis_width

		self.right.setMouseEnabled(x=True, y=False)
		self.left.setMouseEnabled(x=True, y=False)

		self.right_visible = False

	def init_axes(self):
		"""
		Initialize axes
		:returns None
		"""
		self.scene().addItem(self.right)
		self.getAxis("right").linkToView(self.right)
		self.getAxis("right").setTickPen(self.second_axis_color)
		self.getAxis("right").setTextPen(self.second_axis_color)

		self.right.setXLink(self)
		self.right.setZValue(10)

		xmin, xmax = self.left.state["limits"]["xLimits"]
		self.right.setLimits(xMin=xmin, xMax=xmax)

		self.left.sigResized.connect(self.update_views)

	def update_views(self):
		"""
		Readjust geometric of view
		:returns None
		"""
		self.right.setGeometry(self.left.sceneBoundingRect())
		self.right.linkedViewChanged(self.left, self.right.XAxis)

	def add_item_main_axis(self, item):
		"""
		Add viewbox on left
		:param item: viewbox to add
		:returns None
		"""
		self.left.addItem(item)

	def add_item_secondary_axis(self, item):
		"""
		Add and shows secodary item on the right
		:param item: the item
		:returns None
		"""
		if not self.right_visible:
			self.showAxis("right")
			self.right_visible = True

		item.setPen(self.second_axis_color, width=self.second_axis_width)
		self.right.addItem(item)

	def set_secondary_axis_range(self, ymin: float, ymax: float):
		"""
		Set the range of the visible part of view in the right
		:param ymin: The min of range that should be visible along the y-axis.
		:param ymax: The max of range that should be visible along the y-axis.
		:returns None
		"""
		self.right.setRange(yRange=[ymin, ymax])
