#!/usr/bin/env python3

import os
import sys
import time
import subprocess
import serial.tools.list_ports
from test_common import (
    DeviceUnderTestAeadUARTP,
    FileMutex,
    eprint,
    test_main
)


def get_serial():
    import serial.tools.list_ports
    ports = serial.tools.list_ports.comports()
    ports = [
        c
        for c in ports
        if c.product == 'Sipeed-Debug'
    ]
    ports.sort(key=lambda d: d.location)
    return ports[0].device


class Maixduino(DeviceUnderTestAeadUARTP):

    def __init__(self, build_dir):
        DeviceUnderTestAeadUARTP.__init__(self)

        self.uart_device = get_serial()
        devname = os.path.basename(self.uart_device)
        self.lock = FileMutex('/var/lock/lwc-compare.%s.lock' % devname)
        self.build_dir = build_dir
        self.template_path = os.path.dirname(sys.argv[0])

        self.firmware_path = os.path.join(
            build_dir, 'firmware.bin')

    def firmware_size(self):
        return os.stat(self.firmware_path).st_size

    def reset(self):
        if self.ser is not None:
            self.ser.close()
        self.ser = serial.Serial(
            self.uart_device,
            baudrate=1500000,
            timeout=5)

        self.ser.setRTS(True)
        time.sleep(0.1)
        self.ser.setRTS(False)
        time.sleep(0.1)
        self.ser.setRTS(True)
        time.sleep(1)

    def flash(self):
        pio_packages_path = "/home/tester/.platformio/packages/"
        kflash_path = os.path.join(
            pio_packages_path, "tool-kflash-kendryte210/kflash.py")

        cmd = ['python3', kflash_path]
        cmd += ['-b', '750000']
        cmd += ['-p', self.uart_device]
        cmd += ['-B', 'maixduino']
        cmd += [self.firmware_path]
        subprocess.check_call(cmd)

        eprint("Firmware flashed.")

        self.reset()
        self.reset()

    def dump_ram(self):
        return None


if __name__ == "__main__":
    sys.exit(test_main(Maixduino, 0x0080, sys.argv))
