from string import digits

import main
from modules.network import Network
from yaml import dump


class NetworkCommand:
    def __init__(self, *args):
        self.network(*args)

    def network(
        self, addr, authed, data, obj, spl, success, failure, info, incUsage, length
    ):
        if authed:
            if length == 7:
                if spl[1] == "add":
                    if spl[2] in main.network.keys():
                        failure("Network already exists: %s" % spl[2])
                        return
                    if not spl[4].isdigit():
                        failure("Port must be an integer, not %s" % spl[4])
                        return
                    if not spl[5].lower() in ["ssl", "plain"]:
                        failure("Security must be ssl or plain, not %s" % spl[5])
                        return
                    if set(spl[2]).intersection(set(digits)):
                        failure("Network name cannot contain numbers")
                        return
                    if not spl[6].lower() in ["sasl", "ns", "none"]:
                        failure("Auth must be sasl, ns or none, not %s" % spl[5])
                        return
                    else:
                        main.network[spl[2]] = Network(
                            spl[2], spl[3], int(spl[4]), spl[5].lower(), spl[6].lower()
                        )
                        success("Successfully created network: %s" % spl[2])
                        main.saveConf("network")
                        return
                else:
                    incUsage("network")
                    return

            elif length == 3:
                if spl[1] == "del":
                    if spl[2] in main.network.keys():
                        main.network[spl[2]].seppuku()  # ;(
                        del main.network[spl[2]]
                        success("Successfully removed network: %s" % spl[2])
                        main.saveConf("network")
                        return
                    else:
                        failure("No such network: %s" % spl[2])
                        return
                else:
                    incUsage("network")
                    return
            elif length == 2:
                if spl[1] == "list":
                    info(dump(main.network))
                    return
                else:
                    incUsage("network")
                    return
            else:
                incUsage("network")
                return
        else:
            incUsage(None)
