from telnetlib import Telnet
from BotResources import check_negative
from time import sleep

class GQRXHandler():
    def __init__(self, hostname: str = "localhost", port: int = 7356):
        self.hostname = hostname
        self.port = port

        self.tel_conn = None

        self.create_telnet_connection()

    def create_telnet_connection(self):
        print("Creating connection")
        self.tel_conn = Telnet(self.hostname, self.port)
        self.tel_conn.open(self.hostname, self.port)

    def change_freq(self, freq):
        print(f"Changing freq to {freq}")
        self.tel_conn.write(bytes(f"F {int(freq)}", 'utf-8'))
        self.tel_conn.read_until(b'RPRT 0')

    def change_squelch(self, squelch):
        if not check_negative(squelch):
            squelch = float(-abs(squelch))
        print(f"Changing squelch to {squelch}")
        self.tel_conn.write(bytes(f"L SQL {float(squelch)}", 'utf-8'))
        self.tel_conn.read_until(b'RPRT 0')

    def change_mode(self, mode):
        print(f"Changing mode to {mode}")
        self.tel_conn.write(bytes(f"M {str(mode)}", 'utf-8'))
        self.tel_conn.read_until(b'RPRT 0')

    def set_all_settings(self, mode, squelch, freq):
        self.change_squelch(0)
        self.change_mode(mode)
        self.change_freq(freq)
        self.change_squelch(squelch)
