#!/usr/bin/env python

import sys, subprocess, tempfile, time
import subprocess as sp
import wexpect

from ledcontrol import Lighting

# A script to set colors and measure them using a colormunki
# Jacob Joseph
# 12 Sept 2011

class reader(object):
    spot = None

    def __init__(self):
        self.init_spotread()

    def init_spotread(self):
        self.spot = wexpect.spawn("spotread -a -T -H -x")
        self.spot.timeout = 10
        
        self.spot.expect('or hit Esc or Q to abort:')
        self.spot.write('c')
        
        self.spot.expect('Calibration complete')

        print "ready to begin reading" 

    def take_reading(self):
        #print "before", self.spot.before
        #print "after", self.spot.after

        self.spot.write('\n')
        self.spot.flush()

        #time.sleep(5)
        #print "after", self.spot.after

        #print self.spot.read(100)

        self.spot.expect('Yxy:.*Place')

        return self.parse_reading(self.spot.after)


    def parse_reading(self, data):
        # Yxy: 12.038951 0.466255 0.413274
        # Ambient = 37.8 Lux, CCT = 2634K (Delta E 1.570767)
        # Closest Planckian temperature = 2618K (Delta E 0.921523)
        # Closest Daylight temperature  = 2418K (Delta E 1.773022)
        # Color Rendering Index (Ra) = 99.5
        #
        # Place
        
        #print data 
        d = {}
        
        for l in data.split('\r\n'):
            l = l.strip()
            #print l
            if l.startswith('Yxy:'):
                l = l.strip('Yxy:')
                l = l.strip()
                #print l
                Yxy = [float(a) for a in l.split()]
                d['Y'] = Yxy[0]
                d['x'] = Yxy[1]
                d['y'] = Yxy[2]
            elif l.startswith('Ambient'):
                larr = l.split()
                #print larr
                d['ambientlux'] = float(larr[2])
                d['CCT'] = int(larr[6][:-1])
            elif l.startswith('Color Rendering'):
                larr = l.split()
                #print larr
                d['CRI'] = float(larr[5])

        return d




if __name__ == "__main__":
    raw_input("Put meter in calibration position.")
    
    cm = reader()

    lights = Lighting(ledcomm=True, display_plot=False)

    lights.toggle(1)

    off = (0,0,0)

    raw_input("Align reader in ambient mode.")

    result_dict = {}
    log = open('calibrate.log', 'a', buffering=0)

    # take fine readings around the primaries; then the full space at
    # as high a resolution as can actually be completed.  Each read
    # takes around 3 seconds.
    # r = 1.0
    # for g in [float(a)/100 for a in range(11)]:
    #     for b in [float(a)/100 for a in range(11)]:
    #         lights.setcolors(off,off,off,off,(r,g,b))
    #         reading =  cm.take_reading()
    #         result_dict[ (r,g,b)] = reading
    #         print >> log, r,g,b
    #         print >> log, reading

    # g = 1.0
    # for r in [float(a)/100 for a in range(11)]:
    #     for b in [float(a)/100 for a in range(11)]:
    #         lights.setcolors(off,off,off,off,(r,g,b))
    #         reading =  cm.take_reading()
    #         result_dict[ (r,g,b)] = reading
    #         print >> log, r,g,b
    #         print >> log, reading

    # b = 1.0
    # for r in [float(a)/100 for a in range(11)]:
    #     for g in [float(a)/100 for a in range(11)]:
    #         lights.setcolors(off,off,off,off,(r,g,b))
    #         reading =  cm.take_reading()
    #         result_dict[ (r,g,b)] = reading
    #         print >> log, r,g,b
    #         print >> log, reading
                

    # for r in [float(a)/15 for a in range(16)]:
    #     for g in [float(a)/15 for a in range(16)]:
    #         for b in [float(a)/15 for a in range(16)]:
    #             lights.setcolors(off,off,off,off,(r,g,b))
    #             reading =  cm.take_reading()
    #             result_dict[ (r,g,b)] = reading
    #             print >> log, r,g,b
    #             print >> log, reading
                
    # CIE 1931
    # D65 whitepoint: x: 0.3127, y: 0.3290
    # D55 whitepoint: x: 0.33242, y: 0.34743
    # D50 whitepoint: x: 0.34567, y: 0.35850
    
    # import numpy

    # targxy = numpy.array([0.34567, 0.35850])
    # prev = numpy.array([1.0, 1.0, 1.0])
    # new =  numpy.array([1.0, 1.0, 1.0])

    
    # curxy = 

    # while 
        
    
