#!/usr/bin/pythondu
# -*- coding: utf-8 -*-
import math
import pyqtgraph as pg
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph import LinearRegionItem

## local class for drawing GFP frame data
from gfpframe import FrameGraphicsObject
## local class for drawing frame timing
from gfpframetiming import FrameTiming
from gfpconfig import REGION_TIME_RANGE

"""
  extends LinearRegion used to link FramePlot and OverviewPlot
"""
class GFPLinearRegion(pg.LinearRegionItem):
    plot = None  ## FramePlot.plot
    frame_timing = None  ## FramePlot timing ticks

    def __init__(self, plot, initTimeRange):
	pg.LinearRegionItem.__init__(self)

	self.init_time_range = initTimeRange
	self.plot = plot
	self.__setHandlers()

    def addTimingTicks(self, t_data):
        ## frame age timing ticks 
        self.frame_timing = FrameTiming(self.plot, math.ceil(t_data.max()))

    def __setHandlers(self):
       self.sigRegionChanged.connect(self.update)
       self.setZValue(10)
       self.setRegion([0, self.init_time_range])
       self.plot.sigRangeChanged.connect(self.updateRegion)
       
    ## update self.plot view
    def update(self):
       self.setZValue(10)
       minX, maxX = self.getRegion()
       self.plot.setXRange(minX, maxX, padding=0)

    ## update region
    def updateRegion(self, window, viewRange):
       rgn = viewRange[0]
       self.setRegion(rgn)
       ## redraw the frame age boundaries
       if (self.frame_timing is not None):
           self.frame_timing.updateRegion(self.plot.getViewBox().viewRange()[0])

