import os.path

import tron.Misc
from tron import g, hub
from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder
from tron.Hub.Nub.SocketActorNub import SocketActorNub
from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder


name = 'hal'


def start(poller):
    cfg = tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name]

    stop()

    initCmds = ('ping', 'status', 'version')

    safeCmdsList = ['ping', 'version', 'status']
    safeCmds = r'^\s*({0})\s*$'.format('|'.join(safeCmdsList))

    d = ASCIIReplyDecoder(cidFirst=True, debug=1)
    e = ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1)
    nub = SocketActorNub(
        poller,
        cfg['host'],
        cfg['port'],
        name=name,
        encoder=e,
        decoder=d,
        grabCID=True,  # the actor spontaneously generates a line we can eat.
        initCmds=initCmds,
        safeCmds=safeCmds,
        needsAuth=True,
        logDir=os.path.join(g.logDir, name),
        debug=3)
    hub.addActor(nub)


def stop():
    n = hub.findActor(name)
    if n:
        hub.dropActor(n)
        del n

[((540, 581), 'tron.Hub.Reply.Decoders.ASCIIReplyDecoder.ASCIIReplyDecoder', 'ASCIIReplyDecoder', ([], {'cidFirst': '(True)', 'debug': '(1)'}), '(cidFirst=True, debug=1)\n', (557, 581), False, 'from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder\n'), ((590, 648), 'tron.Hub.Command.Encoders.ASCIICmdEncoder.ASCIICmdEncoder', 'ASCIICmdEncoder', ([], {'sendCommander': '(True)', 'useCID': '(False)', 'debug': '(1)'}), '(sendCommander=True, useCID=False, debug=1)\n', (605, 648), False, 'from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder\n'), ((1012, 1029), 'tron.hub.addActor', 'hub.addActor', (['nub'], {}), '(nub)\n', (1024, 1029), False, 'from tron import g, hub\n'), ((1052, 1071), 'tron.hub.findActor', 'hub.findActor', (['name'], {}), '(name)\n', (1065, 1071), False, 'from tron import g, hub\n'), ((1090, 1106), 'tron.hub.dropActor', 'hub.dropActor', (['n'], {}), '(n)\n', (1103, 1106), False, 'from tron import g, hub\n')]