"""Networks plugin - allows you to manipulate connections to various configured networks."""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import threading

import conf
import utils
import world
from log import log

@utils.add_cmd
def disconnect(irc, source, args):
    """<network>

    Disconnects the network <network>. When all networks are disconnected, PyLink will automatically exit.
    Note: This does not affect the autoreconnect settings of any network, so the network will likely just reconnect unless autoconnect is disabled (see the 'autoconnect' command)."""
    utils.checkAuthenticated(irc, source, allowOper=False)
    try:
        netname = args[0]
        network = world.networkobjects[netname]
    except IndexError:  # No argument given.
        irc.reply('Error: Not enough arguments (needs 1: network name (case sensitive)).')
        return
    except KeyError:  # Unknown network.
        irc.reply('Error: No such network "%s" (case sensitive).' % netname)
        return
    irc.reply("Done.")
    # Abort the connection! Simple as that.
    network.aborted.set()

@utils.add_cmd
def connect(irc, source, args):
    """<network>

    Initiates a connection to the network <network>."""
    utils.checkAuthenticated(irc, source, allowOper=False)
    try:
        netname = args[0]
        network = world.networkobjects[netname]
    except IndexError:  # No argument given.
        irc.reply('Error: Not enough arguments (needs 1: network name (case sensitive)).')
        return
    except KeyError:  # Unknown network.
        irc.reply('Error: No such network "%s" (case sensitive).' % netname)
        return
    if network.connection_thread.is_alive():
        irc.reply('Error: Network "%s" seems to be already connected.' % netname)
    else:  # Reconnect the network!
        network.initVars()
        network.connection_thread = threading.Thread(target=network.connect)
        network.connection_thread.start()
        irc.reply("Done.")

@utils.add_cmd
def autoconnect(irc, source, args):
    """<network> <seconds>

    Sets the autoconnect time for <network> to <seconds>.
    You can disable autoconnect for a network by setting <seconds> to a negative value."""
    utils.checkAuthenticated(irc, source, allowOper=False)
    try:
        netname = args[0]
        seconds = float(args[1])
        network = world.networkobjects[netname]
    except IndexError:  # Arguments not given.
        irc.reply('Error: Not enough arguments (needs 2: network name (case sensitive), autoconnect time (in seconds)).')
        return
    except KeyError:  # Unknown network.
        irc.reply('Error: No such network "%s" (case sensitive).' % netname)
        return
    except ValueError:
        irc.reply('Error: Invalid argument "%s" for <seconds>.' % seconds)
        return
    network.serverdata['autoconnect'] = seconds
    irc.reply("Done.")

@@ -2909,28 +2909,1387 @@
 onds%0A    irc.reply(%22Done.%22)%0A
+%0A@utils.add_cmd%0Adef remote(irc, source, args):%0A    %22%22%22%3Cnetwork%3E %3Ccommand%3E%0A%0A    Runs %3Ccommand%3E on the remote network %3Cnetwork%3E. No replies are sent back due to protocol limitations.%22%22%22%0A    utils.checkAuthenticated(irc, source, allowOper=False)%0A%0A    try:%0A        netname = args%5B0%5D%0A        cmd_args = ' '.join(args%5B1:%5D).strip()%0A        remoteirc = world.networkobjects%5Bnetname%5D%0A    except IndexError:  # Arguments not given.%0A        irc.reply('Error: Not enough arguments (needs 2 or more: network name (case sensitive), command name & arguments).')%0A        return%0A    except KeyError:  # Unknown network.%0A        irc.reply('Error: No such network %22%25s%22 (case sensitive).' %25 netname)%0A        return%0A%0A    if not cmd_args:%0A        irc.reply('No text entered!')%0A        return%0A%0A    # Force remoteirc.called_by to something private in order to prevent%0A    # accidental information leakage from replies.%0A    remoteirc.called_by = remoteirc.pseudoclient.uid%0A%0A    # Set PyLink's identification to admin.%0A    remoteirc.pseudoclient.identified = %22%3CPyLink networks.remote override%3E%22%0A%0A    try:  # Remotely call the command (use the PyLink client as a dummy user).%0A        remoteirc.callCommand(remoteirc.pseudoclient.uid, cmd_args)%0A    finally:  # Remove the identification override after we finish.%0A        remoteirc.pseudoclient.identified = False%0A%0A    irc.reply(%22Done.%22)%0A

add "remote" command, for running commands on remote networks