import os, subprocess

DCC_PATH = r".\tools\DeviceCleanupCmd.exe"
LUD_PATH = r".\tools\ListUsbDevs.exe"
RUP_PATH = r".\tools\RestartUsbPort.exe"
DELAY_AFTER_RESTART = 5  # seconds to wait after restarting a USB port


def get_info(search_str):
  assert os.path.exists(LUD_PATH), "Path to ListUsbDevs.exe does not exist"
  cmd = [LUD_PATH, '-na', search_str]
  print("Running command: " + ' '.join(cmd))
  p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

  match_info = {}
  rslt = None
  while rslt is None:
      rslt = p.poll()
      line = p.stdout.readline().decode().rstrip()
      if line == "":
          continue
      print(line)
      if "No matching " in line:
          print("\r\nNo matching devices found")
          return None
      if ": " in line: # parse key/value pairs, removing whitespace from the ends
          key, value = line.split(": ", 1)
          if "USB Port" in key:
              match_info["PortChain"] = value.strip().split("-")
          else:
              match_info[key.strip()] = value.strip()

  assert rslt == 0, p.stderr.readline().decode().rstrip()
  return match_info


def restart_port(search_str):
  assert os.path.exists(RUP_PATH), "Path to RestartUsbPort.exe does not exist"
  cmd = [RUP_PATH, '-n', '-na', f"-w:{DELAY_AFTER_RESTART * 1000}", search_str]
  print("Running command: " + ' '.join(cmd))
  p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

  ret = False
  rslt = None
  while rslt is None:
      rslt = p.poll()
      line = p.stdout.readline().decode().rstrip()
      if line == "":
          continue
      print(line)
      if "success" in line: # parse key/value pairs, removing whitespace from the ends
          ret = True

  assert rslt == 0, p.stderr.readline().decode().rstrip()
  return ret


def cleanup_beyond_devices(log_info, log_debug):
    log_info("Performing device cleanup")
    cmd = [DCC_PATH, '-na', '-s', "SWD\\MMDEVAPI*0.0.1*", "SWD\\MMDEVAPI*0.0.0*", "*VID_28DE*PID_2102*", "*VID_28DE*PID_2300*", "*VID_0424*PID_3803*", "*VID_35BD*"]
    print("Opening command: " + ' '.join(cmd))
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

    rslt = None
    while rslt is None:
        rslt = p.poll()
        line = p.stdout.readline().decode().rstrip()
        if line == "" or "OK" in line:
            continue
        print(line)
        log_debug("Device Cleanup: " + line)
        if "Removed " in line:
            print("\r\n")
            log_info("Device Cleanup: " + line)
    assert rslt == 0, p.stderr.readline().decode().rstrip()