from string import digits

import main
import modules.counters as count
import modules.userinfo as userinfo


class StatsCommand:
    def __init__(self, *args):
        self.stats(*args)

    def stats(
        self, addr, authed, data, obj, spl, success, failure, info, incUsage, length
    ):
        if authed:
            if length == 1:
                stats = []
                numChannels = 0
                numWhoEntries = 0
                for i in main.IRCPool.keys():
                    numChannels += len(main.IRCPool[i].channels)
                numWhoEntries += userinfo.getNumTotalWhoEntries()
                stats.append("Registered servers:")
                stats.append("    Unique: %s" % len(main.network.keys()))
                stats.append("Online servers:")
                stats.append("    Total: %s" % len(main.IRCPool.keys()))
                stats.append("    Unique: %s" % len(main.liveNets()))
                stats.append("Channels: %s" % numChannels)
                stats.append("User records: %s" % numWhoEntries)
                stats.append("Events/min: %s" % main.lastMinuteSample)
                counterEvents = count.getEvents()
                if counterEvents is None:
                    stats.append("No counters records")
                else:
                    stats.append("Counters:")
                    for i in counterEvents.keys():
                        stats.append("    %s: %s" % (i, counterEvents[i]))
                info("\n".join(stats))
                return

            elif length == 2:
                stats = []
                numChannels = 0
                numWhoEntries = 0
                found = False
                numNodes = 0

                for i in main.IRCPool.keys():
                    if "".join([x for x in i if x not in digits]) == spl[1]:
                        numChannels += len(main.IRCPool[i].channels)
                        found = True
                        numNodes += 1
                if not found:
                    failure("Name does not exist: %s" % spl[1])
                numWhoEntries += userinfo.getNumWhoEntries(spl[1])
                stats.append("Channels: %s" % numChannels)
                stats.append("User records: %s" % numWhoEntries)
                stats.append("Endpoints: %s" % numNodes)
                counterEvents = count.getEvents(spl[1])
                if counterEvents is None:
                    stats.append("No counters records")
                else:
                    stats.append("Counters:")
                    for i in counterEvents.keys():
                        stats.append("    %s: %s" % (i, counterEvents[i]))
                info("\n".join(stats))
                return
            else:
                incUsage("stats")
        else:
            incUsage(None)
