import argparse

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


def generate_sine_wave(v: float, freq: int, phase: int):
    fg = DG2052("TCPIP::192.168.1.11::INSTR")
    channel = 2
    v = get_preamplified(AMPLIFICATION, v)
    try:
        print(fg.whoami())
        print("")
        fg.set_sine_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):.2f} V | Pre_amplified: {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="This program is for testing the DG2052 function genrator library. It generates a sine wave with the supplied parameters."
    )
    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 sine 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_sine_wave(
        v=args.voltage, freq=args.freq, phase=args.phase
    )
