import main
import modules.regproc
from twisted.internet import reactor
from utils.deliver_relay_commands import deliverRelayCommands
from utils.logging.log import warn


def provisionUserNetworkData(
    num, nick, altnick, ident, realname, network, host, port, security
):
    commands = {}
    stage2commands = {}
    stage2commands["status"] = []
    commands["controlpanel"] = []
    user = nick.lower()
    commands["controlpanel"].append(
        "AddUser %s %s" % (user, main.config["Relay"]["Password"])
    )
    commands["controlpanel"].append("AddNetwork %s %s" % (user, network))
    commands["controlpanel"].append("Set Nick %s %s" % (user, nick))
    commands["controlpanel"].append("Set Altnick %s %s" % (user, altnick))
    commands["controlpanel"].append("Set Ident %s %s" % (user, ident))
    commands["controlpanel"].append("Set RealName %s %s" % (user, realname))
    if security == "ssl":
        commands["controlpanel"].append(
            "SetNetwork TrustAllCerts %s %s true" % (user, network)
        )  # Don't judge me
        commands["controlpanel"].append(
            "AddServer %s %s %s +%s" % (user, network, host, port)
        )
    elif security == "plain":
        commands["controlpanel"].append(
            "AddServer %s %s %s %s" % (user, network, host, port)
        )
    if not main.config["ConnectOnCreate"]:
        stage2commands["status"].append("Disconnect")
    if main.config["Toggles"]["CycleChans"]:
        stage2commands["status"].append("LoadMod disconkick")
    stage2commands["status"].append("LoadMod chansaver")
    inst = modules.regproc.selectInst(network)
    if "setmode" in inst.keys():
        stage2commands["status"].append("LoadMod perform")
        # stage2commands["perform"].append("add mode %nick% +"+inst["setmode"])
    deliverRelayCommands(num, commands, stage2=[[user + "/" + network, stage2commands]])


def provisionAuthenticationData(num, nick, network, auth, password):
    commands = {}
    commands["status"] = []
    user = nick.lower()
    if auth == "sasl":
        commands["sasl"] = []
        commands["status"].append("UnloadMod nickserv")
        commands["status"].append("LoadMod sasl")
        commands["sasl"].append("Mechanism plain")
        commands["sasl"].append("Set %s %s" % (nick, password))
    elif auth == "ns":
        commands["nickserv"] = []
        commands["status"].append("UnloadMod sasl")
        commands["status"].append("LoadMod nickserv")
        commands["nickserv"].append("Set %s" % password)
    inst = modules.regproc.selectInst(network)
    if "setmode" in inst.keys():
        # perform is loaded above
        # commands["status"].append("LoadMod perform")
        commands["perform"] = ["add mode %nick% +" + inst["setmode"]]
    deliverRelayCommands(num, commands, user=user + "/" + network)


def provisionRelay(num, network):  # provision user and network data
    aliasObj = main.alias[num]
    # alias = aliasObj["nick"]
    nick = aliasObj["nick"]
    altnick = aliasObj["altnick"]
    ident = aliasObj["ident"]
    realname = aliasObj["realname"]
    provisionUserNetworkData(
        num,
        nick,
        altnick,
        ident,
        realname,
        network,
        main.network[network].host,
        main.network[network].port,
        main.network[network].security,
    )
    if main.config["ConnectOnCreate"]:
        reactor.callLater(10, main.network[network].start_bot, num)


def provisionMultipleRelays(net, relaysNeeded):
    if not relaysNeeded:
        return []
    if not main.config["ChanKeep"]["Provision"]:
        warn(
            f"Asked to create {relaysNeeded} relays for {net}, but provisioning is disabled"
        )
        return []
    numsProvisioned = []
    for i in range(relaysNeeded):
        num, alias = main.network[net].add_relay()
        numsProvisioned.append(num)
        provisionRelay(num, net)
    main.saveConf("network")
    return numsProvisioned
