#  Copyright (C) 2024  Minecon724
#  Tweaks724 is licensed under the GNU General Public License. See the LICENSE.md file
#  in the project root for the full license text.

import socket, struct

ENDPOINT = ("127.0.0.1", 57931)

def get_power(repeater_id: int) -> int | None:
    message = repeater_id & 0x7FFFFFF0

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(message.to_bytes(4), ENDPOINT)

    return struct.unpack(">b", sock.recvfrom(1)[0])[0]

def set_power(repeater_id: int, power: int):
    message = repeater_id & 0x7FFFFFF0
    message |= 0x80000000
    message |= power & 0xF

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(message.to_bytes(4), ENDPOINT)


if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument("repeater_id", help="The repeater ID", type=int)
    parser.add_argument("-p", "--power", help="Power the repeater with specified power. Leave to read.", type=int)
    parser.add_argument("-c", "--copy", help="Copy input of one repeater to another. If combined with power, power is added.", type=int)
    args = parser.parse_args()

    if args.copy is None:
        if args.power is None:
            power = get_power(args.repeater_id)
            print(power)
        else:
            set_power(args.repeater_id, args.power)
    else:
        while True:
            power = get_power(args.repeater_id)
            set_power(args.copy, power)