import logging
import logging.config
import logging.handlers
import os
import sys
import time
from datetime import datetime


class FilterInfo:
    def filter(self, rec):
        return rec.levelno <= logging.INFO


formatter = logging.Formatter('[%(asctime)s] %(levelname)s :: %(name)s -> %(message)s', datefmt="%d.%m.%Y %H:%M:%S")
name = "bot"
# As the core is able to host multiple bots out of the same directory, filtering the logs only sounds reasonable.
# So we're saving the logs into ./logs/##bot_name##/
if len(sys.argv) > 1:
    name = sys.argv[1]

try:
    os.mkdir(f"./logs", mode=4600)
except FileExistsError as error:
    pass
try:
    os.mkdir(f"./logs/{name}", mode=4600)
except FileExistsError as error:
    pass

# Rotate logs at 0 a.m. on Monday, GMT-0
file_handler = logging.handlers.TimedRotatingFileHandler(f"./logs/{name}/bot.log",
                                                         when='W6', utc=True,
                                                         backupCount=1000, encoding="utf-8")
file_handler.setFormatter(formatter)

# Fix time display => UTC-0
logging.Formatter.converter = lambda *args: datetime.utcnow().timetuple()

console_out = logging.StreamHandler(sys.stdout)
console_out.setFormatter(formatter)
# noinspection PyTypeChecker
console_out.addFilter(FilterInfo())

console_err = logging.StreamHandler(sys.stderr)
console_err.setFormatter(formatter)
console_err.setLevel(logging.WARN)

logging.root.setLevel(logging.INFO)
logging.root.addHandler(file_handler)
logging.root.addHandler(console_out)
logging.root.addHandler(console_err)

current_time = int(time.time())
# noinspection PyUnresolvedReferences
rollover_time = file_handler.computeRollover(current_time)
logging.info("Next log rollover has been scheduled for " + str(datetime.utcfromtimestamp(rollover_time)))

# reduce discord spam
# logging.getLogger("websockets").setLevel(logging.INFO)
# logging.getlogger("discord").setLevel(logging.INFO)

# Supress Spam generated by using TOR
# [used in: character_history_service.py & tower_service.py
logging.getLogger("torpy.stream").setLevel(logging.WARN)
logging.getLogger("torpy.guard").setLevel(logging.WARN)
logging.getLogger("torpy.consesus").setLevel(logging.WARN)
logging.getLogger("torpy.circuit").setLevel(logging.WARN)
logging.getLogger("torpy.cache_storage").setLevel(logging.WARN)
logging.getLogger("torpy.documents.network_status").setLevel(logging.WARN)
