#!/usr/bin/env python3

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


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 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


def main(argv):
    if len(argv) != 2:
        print("Usage: test build_dir")
        return 1

    build_dir = argv[1]
    kat_path = os.path.join(build_dir, 'LWC_AEAD_KAT.txt')

    dut = Maixduino(build_dir)
    run_nist_lws_aead_test(dut, kat_path, build_dir, 0x0080)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))