#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
  frame age lines
"""
import pyqtgraph as pg
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore

from gfpconfig import FRAME_AGE, MAX_TIMING_RANGE, SEC_TO_MS

"""
  display vertical lines to represent frame timing markers
  within the current view 
"""
class FrameTiming():
    ## maximum allow frame age (size in milliseconds, e.g., 25ms)
    frame_age = (FRAME_AGE * SEC_TO_MS)
    ## array of pg.LineItems created to represent frame age boundaries
    age_lines = []
    ypen = pg.mkPen(color='y', style=QtCore.Qt.DotLine)

    ## t_max - maximum value for t_data 
    def __init__(self, plot, t_max):
       self.plot = plot
       # point on the x-axis where vertical frame age timer tick will be placed
       self.age_points = np.linspace(0, t_max, (t_max / self.frame_age), endpoint=False) 

    def updateRegion(self, viewRegion):
       ## remove lines
       for line in self.age_lines:
          self.plot.removeItem(line)
       self.age_lines = []

       ## skip if the view region is greater than 500ms
       if (viewRegion[1] - viewRegion[0] > MAX_TIMING_RANGE):
          return

       ## plot lines
       idx = self.__find_nearest(self.age_points, viewRegion[0])

       while (True):
          self.age_lines.append(self.plot.addLine(x = self.age_points[idx], pen=self.ypen, movable=False))
          idx += 1
          if (self.age_points[idx] > viewRegion[1]):
             break
    
    ## find nearest frame_age[idx] given x coordinate
    def __find_nearest(self, array,value):
       idx = (np.abs(array-value)).argmin()
       return idx

