import os
import sys
import time
from ctypes import *
from datetime import datetime
from time import sleep

# sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

import pandas as pd
from lib.TLPM import TLPM
from tqdm import tqdm

print("Connecting to PowerMeter.")

tlPM = TLPM()

deviceCount = c_uint32()
tlPM.findRsrc(byref(deviceCount))

print("Number of found devices: " + str(deviceCount.value))
print("")

resourceName = create_string_buffer(1024)

for i in range(0, deviceCount.value):
    tlPM.getRsrcName(c_int(i), resourceName)
    print("Resource name of device", i, ":", c_char_p(resourceName.raw).value)
print("")
tlPM.close()

# Connect to last device.
tlPM = TLPM()
tlPM.open(resourceName, c_bool(True), c_bool(True))

message = create_string_buffer(1024)
tlPM.getCalibrationMsg(message)
print("Connected to device", i)
print("Last calibration date: ",c_char_p(message.raw).value)
print("")

print("Connecting upSERIES.")
#Loading DLL file.
lib = cdll.LoadLibrary("C:\Program Files\IVI Foundation\VISA\Win64\Bin\TLUP_64.dll")




#Counting upSeries devices.
deviceCount = c_uint32()
lib.TLUP_findRsrc(0,byref(deviceCount))
if deviceCount.value > 0:
    print("Number of upSeries devices found: " + str(deviceCount.value))
else:
    print("No upSeries devices found.")
    exit()
print()

#Reading model name and serial number of the first connected upSeries device.
modelName = create_string_buffer(256)
serialNumber = create_string_buffer(256)
lib.TLUP_getRsrcInfo(1, 3, modelName, serialNumber, 0, 0)
print("Connecting to this device:")
print("Model name: ", (modelName.value).decode(), ", Serial number: ", (serialNumber.value).decode())
print()

upNames = [0 for i in range(deviceCount.value)]
upHandles = [0 for i in range(deviceCount.value)]

for i in range(deviceCount.value):
    print(i)
    #Initializing the first connected upSeries device.
    upNames[i] = create_string_buffer(256)
    lib.TLUP_getRsrcName(0, i, upNames[i])
    upHandles[i]=c_int(0)
    res=lib.TLUP_init(upNames[i].value, 0, 0, byref(upHandles[i]))
    print(f"uphandle is: {upHandles[i] , upHandles[i].value} for {upNames[i].value}")

sleep(1)

data = dict()

file_name = input("Write filename for datafile (will be stored in /automation/logs/pm/.): ")

for i in range(deviceCount.value):
    #LED SETTINGS
    upHandle = upHandles[i]
    print(lib.TLUP_setLedUseNonThorlabsLed(upHandle, 1))
    lib.TLUP_switchLedOutput(upHandle,0)
    currentSetpoint = c_double()
    LEDName = create_string_buffer(256)
    LEDSerialNumber = create_string_buffer(256)
    LEDCurrentLimit = c_double()
    LEDForwardVoltage = c_double()
    LEDWavelength = c_double(0)

    lib.TLUP_getLedInfo(upHandle, LEDName, LEDSerialNumber, byref(LEDCurrentLimit),
                        byref(LEDForwardVoltage), byref(LEDWavelength))
    if LEDWavelength.value != 0:
        pass
    else:
        print("Something wrong with the LEDs.")
        exit()
    # POWER METER SETTINGS
    tlPM.setWavelength(c_double(LEDWavelength.value))
    tlPM.setPowerAutoRange(c_int16(1))
    tlPM.setPowerUnit(c_int16(0))
    

    ######################
    print("EEPROM on LED detected.")
    print("Connected LED:", (LEDName.value).decode(), ", serial number:", (LEDSerialNumber.value).decode(),", wavelength [nm]:",LEDWavelength.value)
    print("max LED current [A]:", LEDCurrentLimit.value, ", max forward voltage [V]:", LEDForwardVoltage.value)
    print()
    data[f"{LEDWavelength.value}_i"] = []
    data[f"{LEDWavelength.value}_p"] = []
    lower = 20
    higher = int(LEDCurrentLimit.value*1000)
    low_range = range(20,100,10)
    for x in range(lower,higher+1):
        if x % 100 == 0 or x in low_range:
            #Set the current setpoint in Ampere to 10% of the current limit of this LED.
            currentSetpoint = c_double((0.001) * x)
            print(currentSetpoint)
            lib.TLUP_setLedCurrentSetpoint(upHandle,currentSetpoint)
            time.sleep(1)
            lib.TLUP_getLedCurrentSetpoint(upHandle,0, byref(currentSetpoint))
            print("LED current set to [A]:", currentSetpoint.value)
            # print()
            sleep(0.5)
            lib.TLUP_switchLedOutput(upHandle,1)
            sleep(0.5)
            power = c_double()
            tlPM.measPower(byref(power))
            data[f"{LEDWavelength.value}_i"].append(x)
            data[f"{LEDWavelength.value}_p"].append(power.value)
            print(f"Power is: {power.value}")
            sleep(0.5)
            lib.TLUP_switchLedOutput(upHandle,0)
            sleep(0.5)

    lib.TLUP_close(upHandle)
tlPM.close()
df = pd.DataFrame.from_dict(data,orient="index")
df.transpose()
df.to_csv(f"logs/pm/{file_name}.csv")