import main
from utils.deliver_relay_commands import deliverRelayCommands


class AllcCommand:
    def __init__(self, *args):
        self.allc(*args)

    def allc(
        self, addr, authed, data, obj, spl, success, failure, info, incUsage, length
    ):
        if authed:
            if length > 4:
                targets = []
                if spl[1] == "network":
                    for i in main.network.keys():
                        for x in main.network[i].relays.keys():
                            if main.network[i].relays[x]["net"] == spl[2]:
                                targets.append((i, x))
                elif spl[1] == "alias":
                    for i in main.network.keys():
                        [
                            targets.append((i, x))
                            for x in main.alias.keys()
                            if main.alias[x]["nick"] == spl[2]
                            and x in main.network[i].aliases.keys()
                        ]
                else:
                    incUsage("allc")
                    return
                if len(targets) == 0:
                    failure("No matches found: %s" % spl[2])
                    return
                for i in targets:
                    net = i[0]
                    num = i[1]
                    alias = main.alias[num]["nick"]
                    commands = {spl[3]: [" ".join(spl[4:])]}
                    success(
                        "Sending commands to relay %i as user %s"
                        % (num, alias + "/" + net)
                    )
                    deliverRelayCommands(num, commands, user=alias + "/" + net)
                return
            else:
                incUsage("allc")
                return
        else:
            incUsage(None)
