import time
import can
import canTest
import struct

bustype = "socketcan"
channel = "can0"


def getBatteryVoltageOverCan():
    bus = can.Bus(channel=channel, interface=bustype)
    message = can.Message(
        arbitration_id=0x002, data=[2, 0, 0, 0, 0, 0, 0], is_extended_id=False
    )
    bus.send(message)
    voltages = []
    runtime = 3
    begin = 0

    for msg in bus:
        # print(msg.data)
        voltages.append(msg.data)
        # print("begin {}".format(begin))
        begin = begin + 1
        if begin > 4:
            return voltages


def verifyNumbers(numberListList):
    zeroCount = 0
    max = 0
    min = 1000000
    for numberList in numberListList:
        for number in numberList:
            if number == 0:
                zeroCount += 1

            elif number < min:
                min = number

            elif number > max:
                max = number

    print("There were 3 expected Zeros and {} detected".format(zeroCount))
    print(
        "The biggest difference were over {} and under {}".format(
            (max - 35000), (35000 - min)
        )
    )


def voltagesTest():
    print("====================")
    print("starting voltage test pls but 3.500 as reference value")
    while True:
        canTest.waitForUserInput(True)
        voltages = getBatteryVoltageOverCan()  # rausfinden welche id der Slave hat
        allVoltages = []
        for volt in voltages:
            allVoltages.append(struct.unpack("<HHHH", volt))

        verifyNumbers(allVoltages)
        print("I am done with this shit")
        if canTest.waitForUserInput(True, "Repeat voltage test?") != 0:
            break
