"""WizardKit: Launch Snappy Driver Installer Origin"""
# vim: sts=2 sw=2 ts=2

from subprocess import CompletedProcess

import wk
from wk.cfg.net import SDIO_SERVER


# STATIC VARIABLES
MOUNT_EXCEPTIONS = (
  RuntimeError,
  wk.exe.subprocess.CalledProcessError,
  )
SDIO_LOCAL_PATH = wk.kit.tools.get_tool_path("SDIO", "SDIO")
SDIO_REMOTE_PATH = wk.io.get_path_obj(
  (
    fr'\\{SDIO_SERVER["Address"]}\{SDIO_SERVER["Share"]}\{SDIO_SERVER["Path"]}'
    fr'\SDIO{"64" if wk.os.win.ARCH == "64" else ""}.exe'
    ),
  resolve=False,
  )

# Functions
def try_again() -> bool:
  """Ask to try again or quit."""
  if wk.ui.cli.ask('  Try again?'):
    return True
  if not wk.ui.cli.ask('  Use local version?'):
    wk.ui.cli.abort()
  return False


def use_network_sdio() -> bool:
  """Try to mount SDIO server."""
  use_network = False
  def _mount_server() -> CompletedProcess:
    print('Connecting to server...  (Press CTRL+c to use local copy)')
    return wk.net.mount_network_share(SDIO_SERVER, read_write=False)

  # Bail early
  if not SDIO_SERVER['Address']:
    return use_network

  # Main loop
  while True:
    try:
      proc = _mount_server()
    except KeyboardInterrupt:
      break
    except MOUNT_EXCEPTIONS as err:
      wk.ui.cli.print_error(f'  {err}')
      if not try_again():
        break
    else:
      if proc.returncode == 0:
        # Network copy available
        use_network = True
        break

      # Failed to mount
      wk.ui.cli.print_error('  Failed to mount server')
      if not try_again():
        break

  # Done
  return use_network


if __name__ == '__main__':
  wk.ui.cli.set_title(
    f'{wk.cfg.main.KIT_NAME_FULL}: Snappy Driver Installer Origin Launcher',
    )
  log_dir = wk.log.format_log_path(tool=True).parent
  USE_NETWORK = False

  # Try to mount server
  try:
    USE_NETWORK = use_network_sdio()
  except KeyboardInterrupt:
    wk.ui.cli.abort()

  # Run SDIO
  EXE_PATH = SDIO_LOCAL_PATH
  if USE_NETWORK:
    EXE_PATH = SDIO_REMOTE_PATH
    print('Using network copy!')
  else:
    print('Using local copy!')
  cmd = [EXE_PATH, '-log_dir', log_dir]
  wk.exe.run_program(cmd, check=False, cwd=EXE_PATH.parent)
