#!/usr/bin/env python

from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

from twisted.internet.protocol import Protocol

class QOTD(Protocol):
    def connectionMade(self):
        self.transport.write("An apple a day keeps the doctor away\r\n".encode("utf-8"))
        self.transport.loseConnection()

class QOTDFactory(Factory):
    def buildProtocol(self, addr):
        return QOTD()


# Why does this seem to be doing line buffering?
# Because telnet defaults to line mode
# ^] 
# telnet> mode character
# or:
# telnet> mode line
# to toggle.  (The echo works correctly, it's the telnet client that's silly.)

class Echo(Protocol):
    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.numProtocols = self.factory.numProtocols + 1
        self.transport.write(
            "Welome! There are currently {0} open connections.\n".format( 
            self.factory.numProtocols ).encode('utf-8') )

    def connectionLost(self, reason):
        self.factory.numProtocols = self.factory.numProtocols - 1

    def dataReceived(self, data):
        self.transport.write(data)


class EchoFactory(Factory):
    def __init__(self):
        self.numProtocols = 0

    def buildProtocol(self, addr):
        return Echo(self)

endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(EchoFactory())
qotdpoint = TCP4ServerEndpoint(reactor, 8008)
qotdpoint.listen(QOTDFactory())
reactor.run()