import argparse
from fn_gen import DG2052
import fn_gen.errors as fg_err
from common import close_output, get_preamplified, get_postamplified, AMPLIFICATION


def generate_square_wave(v: float, freq: int, phase: int):
    """
    This program is for testing the DG2052 function genrator library. It generates a square wave with the supplied parameters.
    """
    fg = DG2052("TCPIP::192.168.1.11::INSTR")
    v = get_preamplified(AMPLIFICATION, v)
    channel = 2
    try:
        print(fg.whoami())
        print(f"\nOutput{channel} Impedance: {fg.get_output_impedance(channel)} Ohm")
        print(f"Output{channel} Load: {fg.get_output_load(channel)} Ohm")
        print(f"Output{channel} Voltage Limits: {fg.get_output_volt_limits(channel)} V")
        fg.set_square_wave(channel, freq, v, 0, phase)
        print(
            f"Output{channel}: {fg.get_output_signal(channel)} | {fg.get_output_state(channel)}"
        )
        fg.set_output(channel, True)
        print(f"Voltage: {get_postamplified(AMPLIFICATION,v)} V")
        print(f"Frequency: {freq} Hz")
        print(f"Output{channel} State: {fg.get_output_state(channel)}")
        while True:
            pass
    except fg_err.ValueOutOfBoundsError as err:
        print(err)
    except fg_err.UndefinedValueError as err:
        print(err)
    except KeyboardInterrupt:
        close_output(fg, channel)
    finally:
        close_output(fg, channel)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="")
    parser.add_argument("-v", "--voltage", type=float, required=True, help="The voltage supplied")
    parser.add_argument(
        "--freq", type=int, default=200, help="The frequency of the square wave generated"
    )
    parser.add_argument(
        "--phase",
        type=int,
        default=0,
        help="The phase shift of the signal generated (must be between 0 and 360)",
    )
    args = parser.parse_args()
    if args.phase not in range(0,360):
        parser.print_help()
        exit(1)
    generate_square_wave(args.voltage, args.freq, args.phase)
