import logging
import os
import sys
import requests

from logstash_async.transport import HttpTransport
from logstash_async.handler import AsynchronousLogstashHandler

EXTENSIVE_LOGGING = os.getenv("EXTENSIVE_LOGGING", "False")

if EXTENSIVE_LOGGING == "True":
    EXTENSIVE_LOGGING = True
else:
    EXTENSIVE_LOGGING = False

host = 'logstash.robo4you.at'
port = 443

logstash_logger = logging.getLogger('logstash')
logstash_logger.setLevel(logging.INFO)

transport = HttpTransport(
    host,
    port,
    username="robo",
    password="competition",
    timeout=60.0,
)

asynchronousLogstashHandler = AsynchronousLogstashHandler(
    host,
    port,
    transport=transport,
    database_path='logs.db'
)


class StreamToLogger(object):
    """
    Fake file-like stream object that redirects writes to a logger instance.
    """

    def __init__(self, textio, log_level=logging.INFO):
        self.logger = logging.getLogger('logstash')
        self.console = textio
        self.log_level = log_level
        self.linebuf = ''

    def write(self, buf):
        self.console.write(buf)
        temp_linebuf = self.linebuf + buf
        for line in buf.splitlines(True):
            self.linebuf += line

    def flush(self):
        if self.linebuf != '':
            self.logger.log(self.log_level, self.linebuf.rstrip())
        self.linebuf = ''
        self.console.flush()
        asynchronousLogstashHandler.flush()


if EXTENSIVE_LOGGING:
    try:
        r = requests.get(f"https://{host}:{port}")
        if r.status_code == 401:
            logstash_logger.addHandler(asynchronousLogstashHandler)

            so = StreamToLogger(sys.stdout, logging.INFO)
            sys.stdout = so

            se = StreamToLogger(sys.stderr, logging.ERROR)
            sys.stderr = se
        else:
            print(f"Could not connect to {host} -> ERROR CODE: {r.status_code}!")

    except requests.exceptions.ConnectionError as identifier:
        print(f"Could not connect to {host}!")
        print(f"Error loading logger was -> {identifier}")
else:
    print("Extensive logging is disabled! No logs will be sent over network...")


class Logging(object):
    """Can be used to manually use the logger or turn up the logging level used for debugging this library.
    """

    @staticmethod
    def get_logger() -> logging.Logger:
        """Get the logger object used to communicate with logstash

        :return: Python logger
        :rtype: logging.Logger
        """
        return logstash_logger

    @staticmethod
    def set_debug():
        """Turns up the logging level of the library to debug. Should be used, when debugging with the
        Competition organizers
        """
        logstash_logger.setLevel(logging.DEBUG)
