import argparse

import fn_gen.errors as fg_err
from fn_gen import DG2052

from common import close_output, get_postamplified, get_preamplified, AMPLIFICATION


def generate_ramp_wave(v, freq, phase):
    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_ramp(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")
        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 ramp 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",
    )
    args = parser.parse_args()
    if args.phase not in range(0, 360):
        parser.print_help()
        exit(1)
    generate_ramp_wave(args.v, args.freq, args.phase)
