#!/usr/bin/env python3

import click
import asyncio
from webfpga           import VERSION
from webfpga.Flash     import Flash
from webfpga.Synthesis import Synthesize
from webfpga.Utilities import SetBitstring

@click.group()
@click.version_option(
        version=VERSION, prog_name="webfpga",
        message="%(prog)s, version %(version)s\n" +
        "Copyright (C) Auburn Ventures, LLC. MIT License.")
def cli():
    print(f"WebFPGA CLI v{VERSION}\n")

# Synthesize
@cli.command()
@click.option("-o", "--output", default="bitstream.bin", help="Bitstream filename", type=click.File("wb"))
@click.option("--no-cache", is_flag=True, help="Disable bitstream caching")
@click.argument("input_verilog", nargs=-1, required=True, type=click.File("r"))
def synth(output, input_verilog, no_cache):
    """Synthesize one or more input Verilog files and save the bitstream"""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(
        Synthesize(input_verilog=input_verilog, output_bitstream=output, no_cache=no_cache)
    )

# Flash
@cli.command()
@click.argument("bitstream", required=True, type=click.File("rb"))
def flash(bitstream):
    """Flash the first connected WebFPGA device"""
    Flash(bitstream.read())

# Set CPU wires
# (External MCU->FPGA one-way communication.)
@cli.command()
@click.argument("bitstring", required=True)
def setbits(bitstring):
    """Set the CPU->FPGA communication bits

    ---

    BITSTRING can be a 4-character string of '0', '1', or 'X'.
    BITSTRING can also be 'init'.

    If the device has just powered on, you need to run `webfpga setbits init`.

    ---

    Examples:

      webfpga setbits init    # Initialize CPU->FPGA communication.

      webfpga setbits 0000    # Set all bits to 0.

      webfpga setbits 0011    # Set the first two bits to 0, last two bits to 1.

      webfpga setbits 1XXX    # Set first bit to 1.

      webfpga setbits X000    # Set last three bits to 0.

    ---
    """
    SetBitstring(bitstring)

cli()
