#! /usr/bin/env python3
import argparse
import sys
import logging
import serial

logger = logging.getLogger(__name__)


def set_apf(s: serial.Serial, state: str) -> None:
    if state == "on":
        s.write(b"AP1;")
    elif state == "off":
        s.write(b"AP0;")


def set_nb(s: serial.Serial, state: str) -> None:
    if state == "on":
        s.write(b"NB1;")
    elif state == "off":
        s.write(b"NB0;")
    else:
        s.write("NL{:0>2}00;".format(state).encode("ascii"))
        s.write(b"NB1;")


def set_preamp(s: serial.Serial, state: str) -> None:
    if state == "on":
        s.write(b"PA1;")
    elif state == "off":
        s.write(b"PA0;")


def set_attenuator(s: serial.Serial, state: str) -> None:
    if state == "on":
        s.write(b"RA01;")
    elif state == "off":
        s.write(b"RA00;")


def set_filter_bandwidth(s: serial.Serial, bandwidth: float) -> None:
    s.write("BW{:0>4};".format(int(bandwidth * 100)).encode("ascii"))


def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="kxfilter", description="Change filter settings on a KX2 or KX3"
    )
    ap.add_argument(
        "--audio-peaking-filter",
        "--apf",
        help="Control the Audio Peaking Filter",
        choices=["on", "off"],
    )
    ap.add_argument(
        "--noise-blanker",
        "--nb",
        help="Control the noise blanker",
        choices=["on", "off"] + [str(x) for x in range(0, 16)],
    )
    ap.add_argument(
        "--pre-amp", "--pa", help="Control the pre-amp", choices=["on", "off"]
    )
    ap.add_argument(
        "--attenuator", "--att", help="Control the attenuator", choices=["on", "off"]
    )
    ap.add_argument(
        "--filter-bandwidth",
        "--bw",
        help="Filter bandwidth",
        type=float,
        choices=[
            0.05,
            0.10,
            0.15,
            0.20,
            0.25,
            0.30,
            0.35,
            0.40,
            0.45,
            0.5,
            0.6,
            0.7,
            0.8,
            0.9,
            1.0,
            1.2,
            1.4,
            1.6,
            2.0,
            2.4,
            2.8,
        ],
    )
    ap.add_argument("--device", "-d", help="Serial device", default="/dev/ttyUSB0")
    ap.add_argument("--baud", "-b", help="Serial baud rate", default=38400, type=int)
    ap.add_argument(
        "-v", "--verbose", help="Enable verbose logging", action="store_true"
    )
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(levelname)s:	%(message)s",
        stream=sys.stderr,
    )

    # Connect to the radio
    logger.debug(f"Connecting to radio: {args.device}")
    serial_conn = serial.Serial(args.device, args.baud)

    # Handle APF
    if args.audio_peaking_filter:
        logger.info(f"Setting APF: {args.audio_peaking_filter}")
        set_apf(serial_conn, args.audio_peaking_filter)

    # Handle NB
    if args.noise_blanker:
        logger.info(f"Setting Noise Blanker: {args.noise_blanker}")
        set_nb(serial_conn, args.noise_blanker)

    # Handle PA
    if args.pre_amp:
        logger.info(f"Setting Pre-Amp: {args.pre_amp}")
        set_preamp(serial_conn, args.pre_amp)

    # Handle RX ATT
    if args.attenuator:
        logger.info(f"Setting RX Attenuator: {args.attenuator}")
        set_attenuator(serial_conn, args.attenuator)

    # Handle filter bandwidth
    if args.filter_bandwidth:
        logger.info(f"Setting Filter Bandwidth: {args.filter_bandwidth}")
        set_filter_bandwidth(serial_conn, args.filter_bandwidth)

    return 0


if __name__ == "__main__":
    sys.exit(main())