from . import ardice
from stardice import keithley
import numpy as np
from glob import glob
import time
from . import sp_dk240
import xmlrpc.client


template = 'asispectrum_'
existing_files = glob(template +'*.npy')
existing_files = [int(f.replace('.npy', '').replace(template, '')) for f in existing_files]

if not existing_files:
    print('Warning: first file in the seri')
    odometer = 0
else:
    odometer = np.max(existing_files) + 1

k = keithley.Keithley6514('/dev/ttyUSB1')
nsamples = 10
k.setup(krange=2e-5, samples=nsamples)

M = sp_dk240.Monochromator('/dev/ttyUSB0')
M.open()

ar = ardice.Ardice()
ar.all_led_off()


c = xmlrpc.client.ServerProxy('http://localhost:8910')
c.connect()
try:
    c.default()
except:
    c.connect()
    c.default()
c.set_exptime(1000000)

#nrepeat =400
#nrepeat = 2
#length = 10
result = []
def takeone():
    t1 = time.time()
    k.non_blocking_read(repeats=1)
    phd = c.photodiode()
    temp = c.get_temperature()
    on = k.join()
    t2 = time.time()
    return t1, t2, phd, temp, on

try:
    for led in range(16):
        print('taking dark')
        t1, t2, phd, temp, on = takeone()
        result.append([0, 0, t1, t2, np.min(on[1]), np.max(on[1]), np.mean(on[0]), np.std(on[0])/np.sqrt(nsamples), phd, temp])
        ar.led_on(led)
        time.sleep(120)
        for wl in np.arange(300, 1100):
            print(('WAVELENGTH: %d' % wl))
            M.set_wavelength(wl)
            t1, t2, phd, temp, on = takeone()
            result.append([led, wl, t1, t2, np.min(on[1]), np.max(on[1]), np.mean(on[0]), np.std(on[0])/np.sqrt(nsamples), phd, temp])
        ar.led_off(led)
        time.sleep(2)
        t1, t2, phd, temp, on = takeone()
        result.append([0, 0, t1, t2, np.min(on[1]), np.max(on[1]), np.mean(on[0]), np.std(on[0])/np.sqrt(nsamples), phd, temp])
finally:
    result = np.rec.fromrecords(result, names=['led', 'wl', 't1', 't2', 'tk1', 'tk2', 'phd', 'phde', 'cam', 'tempcam'])
    del ar

np.save(template+'%04d.npy' % odometer, result)
