#!/usr/bin/env python3

import pprint
import os
import sys
import time
import datetime
import re
import numpy
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.backends.backend_pdf import PdfPages

import testing

class PlotTrayMap:
  ''' Class with basics to plot a full tray '''
  def __init__(self, rows = 18, columns = 7, outputFile = 'result.pdf'):
    self.scale = 1
    self.rows = rows
    self.columns = columns
    self.colorGrid = '#aaaaaa'
    self.geometry = (rows*self.scale, columns*self.scale)
    #
    self.fig = plt.figure(1, self.geometry)
    self.ax = self.fig.add_subplot(111)
    self.pdf = PdfPages(outputFile)
    self.ax.set_xlabel('Rows')
    self.ax.set_ylabel('Columns')
    self.ax.set_xlim(.5*self.scale, rows + .5*self.scale)
    self.ax.set_ylim(.5*self.scale, columns + .5*self.scale)
    self.ax.yaxis.set_minor_locator(ticker.FixedLocator(list([i + .5*self.scale for i in range(0, columns + 1)])))
    self.ax.xaxis.set_minor_locator(ticker.FixedLocator(list([i + .5*self.scale for i in range(0, rows + 1)])))
    self.ax.grid(clip_on = True, color = self.colorGrid, which = 'minor', axis = 'both')

  def __del__(self):
    self.pdf.savefig(self.fig)
    self.pdf.close()
    plt.close()

  def addText(self, row, column, txt = 'Some text', zorder = 5):
    self.ax.text(row, column, txt, ha = 'center', va = 'center',
                 zorder = zorder, fontsize = 8)

  def addRectangle(self, row, column, color = 'orange', zorder = 0):
    box = plt.Rectangle(((row-.5)*self.scale, (column-.5)*self.scale), self.scale, self.scale,
                        alpha = .5, zorder = zorder,
                        facecolor = color, edgecolor = self.colorGrid
                       )
    self.ax.add_patch(box)

  def addTitle(self):
    plt.title('SAMPA tray scan ' + str(datetime.datetime.now()))

  def plot(self, results):
    ''' Take result list from scan and generate output plot '''
    self.addTitle()

    for e in results:
      color = str()
      txt = str()

      if (e['id'] == None):
        color = '#cccccc'
        txt = 'Empty'
      else:
        color = '#888888'
        rm = re.match("(SAMPA) (V[\d]+G[\d]+[B|F|M][\d]+)(\.)([\d]+)(\/)(\d\d)([\d]+)", e['id'])
        #print(rm, rm.groups())
        txt = rm.group(1) + '\n' +\
              rm.group(2) + '\n' +\
              rm.group(4) + rm.group(5) + rm.group(6) + '\n' +\
              rm.group(7)

      self.addRectangle(e['row'], e['column'], color = color)
      self.addText(e['row'], e['column'], txt = txt)

  def plotNonUniqueFailList(self, failList):
    ''' Take list of chips with identical ID and plot the results
          Identical IDs are marked in red
    '''
    for e in failList:
      first, second = e
      self.addRectangle(first['row'], first['column'], color = 'red')
      self.addRectangle(second['row'], second['column'], color = 'red')


#--------------------------------------------------------------------------------
def main():
  p = PlotTrayMap()
  p.plot(testing.testResult)
  p.plotNonUniqueFailList(testing.testNonUniqueFailList)

#--------------------------------------------------------------------------------
if __name__ == "__main__":
  main()
