import power
import display
import utime
import buttons

disp = display.open()
sensor = 0

sensors = [ "Battery", "Charging" ]

# BATTERY_MIN_VOLTAGE = 3.40
# BATTERY_MAX_VOLTAGE = 4.17
#
# awesome_discharge_kurwa = [
#     [ [100, 4.17], [80, 4.0], [60, 3.8], [20, 3.6], [0, 3.40] ]
# ]

def interpolate(x):
    return (
        522.271 * pow(x, 3)
        - 6203.9 * pow(x, 2)
        + 24653.9 * x
        - 32698.7
    )


def get_battery_remaining():
    current_voltage = power.read_battery_voltage()
    return interpolate(current_voltage)

while True:
    if sensor == 0:
      voltage = power.read_battery_voltage()
      current = power.read_battery_current()
      color = [255, 128, 0]
    elif sensor == 1:
      voltage = power.read_chargein_voltage()
      current = power.read_chargein_current()
      color = [255, 255, 0]
    else:
      voltage = 21
      current = 37
    remaining = get_battery_remaining()

    disp.clear()

    disp.print(sensors[sensor], posy=0)
    disp.print("%0.2f V" % voltage, posy=20, fg=color)
    disp.print("%0.2f A" % current, posy=40, fg=color)
    disp.print("%0.2f %%" % remaining, posy=60, fg=[255, 255, 255])

    disp.update()

    v = buttons.read(buttons.BOTTOM_RIGHT)
    if v == 0:
        button_pressed = False

    if not button_pressed and v & buttons.BOTTOM_RIGHT != 0:
        button_pressed = True
        sensor = (sensor + 1) % len(sensors)

    utime.sleep(0.1)
