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

logger = logging.getLogger(__name__)


def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="kxchat", description="Chat over CW using the keyboard"
    )
    ap.add_argument("--tx-only", help="Only transmit, do not receive", action="store_true")
    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,
    )

    # Spawn a kxlisten process and hook its STDOUT to our STDOUT
    if not args.tx_only:
        logger.debug(f"Starting kxlisten process")
        kxlisten = subprocess.Popen(
            ["kxlisten", "-d", args.device, "-b", str(args.baud)],
        )
    
    # Read lines from keyboard, and send them to the radio using kxsend
    try:
        while True:
            # Read a line from the keyboard
            line = sys.stdin.readline().strip()
            
            # If the line is empty, skip
            if not line:
                continue
            
            # Add a space onto the end of the line 
            line += " "
            
            # Send the line to the radio
            logger.debug(f"Sending line: {line}")
            kxsend = subprocess.Popen(
                ["kxsend", "-d", args.device, "-b", str(args.baud), line],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            
    except KeyboardInterrupt:
        logger.info("Done transmitting")
        
    # Stop the kxlisten process
    if not args.tx_only:
        logger.debug(f"Stopping kxlisten process")
        kxlisten.terminate()

    return 0


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