import logging

def get_logger(env):
  logger = logging.getLogger("utils")
  lvl = env.NBOX_LOG_LEVEL("info").upper()
  logger.setLevel(getattr(logging, lvl))

  if env.NBOX_JSON_LOG(False):
    logHandler = logging.StreamHandler()
    logHandler.setFormatter(JsonFormatter(
      '%(timestamp)s %(levelname)s %(message)s %(filename)s %(lineno)d',
      timestamp=True
    ))
    logger.addHandler(logHandler)
  else:
    logHandler = logging.StreamHandler()
    logHandler.setFormatter(logging.Formatter(
      '[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
      datefmt = "%Y-%m-%dT%H:%M:%S%z"
    ))
    logger.addHandler(logHandler)

  return logger



##############
# custom logger class for simplicity
class NBXUnifiedLogger:
  def __init__(self, env):
    self._logger = get_logger(env)
    self.json = env.NBOX_JSON_LOG(False)

  def construct(self, msg, *args):
    if self.json:
      return msg
    return msg + " " + " ".join(args)

  def debug(self, msg, *args):
    self._logger.debug(self.construct(msg, *args))
  
  def info(self, msg, *args):
    self._logger.info(self.construct(msg, *args))

  def warning(self, msg, *args):
    self._logger.warning(self.construct(msg, *args))

  def error(self, msg, *args):
    self._logger.error(self.construct(msg, *args))

  def critical(self, msg, *args):
    self._logger.critical(self.construct(msg, *args))


##############

'''
This library is provided to allow standard python logging
to output log data as JSON formatted strings
'''
import logging
import json
import re
from datetime import date, datetime, time, timezone
import traceback
import importlib

from inspect import istraceback

from collections import OrderedDict

# skip natural LogRecord attributes
# http://docs.python.org/library/logging.html#logrecord-attributes
RESERVED_ATTRS = (
  'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',
  'funcName', 'levelname', 'levelno', 'lineno', 'module',
  'msecs', 'message', 'msg', 'name', 'pathname', 'process',
  'processName', 'relativeCreated', 'stack_info', 'thread', 'threadName')


def merge_record_extra(record, target, reserved):
  """
  Merges extra attributes from LogRecord object into target dictionary

  :param record: logging.LogRecord
  :param target: dict to update
  :param reserved: dict or list with reserved keys to skip
  """
  for key, value in record.__dict__.items():
    # this allows to have numeric keys
    if (key not in reserved
      and not (hasattr(key, "startswith")
           and key.startswith('_'))):
      target[key] = value
  return target


class JsonEncoder(json.JSONEncoder):
  """
  A custom encoder extending the default JSONEncoder
  """

  def default(self, obj):
    if isinstance(obj, (date, datetime, time)):
      return self.format_datetime_obj(obj)

    elif istraceback(obj):
      return ''.join(traceback.format_tb(obj)).strip()

    elif type(obj) == Exception \
        or isinstance(obj, Exception) \
        or type(obj) == type:
      return str(obj)

    try:
      return super(JsonEncoder, self).default(obj)

    except TypeError:
      try:
        return str(obj)

      except Exception:
        return None

  def format_datetime_obj(self, obj):
    return obj.isoformat()


class JsonFormatter(logging.Formatter):
  """
  A custom formatter to format logging records as json strings.
  Extra values will be formatted as str() if not supported by
  json default encoder
  """

  def __init__(self, *args, **kwargs):
    """
    :param json_default: a function for encoding non-standard objects
      as outlined in http://docs.python.org/2/library/json.html
    :param json_encoder: optional custom encoder
    :param json_serializer: a :meth:`json.dumps`-compatible callable
      that will be used to serialize the log record.
    :param json_indent: an optional :meth:`json.dumps`-compatible numeric value
      that will be used to customize the indent of the output json.
    :param prefix: an optional string prefix added at the beginning of
      the formatted string
    :param rename_fields: an optional dict, used to rename field names in the output.
      Rename message to @message: {'message': '@message'}
    :param static_fields: an optional dict, used to add fields with static values to all logs
    :param json_indent: indent parameter for json.dumps
    :param json_ensure_ascii: ensure_ascii parameter for json.dumps
    :param reserved_attrs: an optional list of fields that will be skipped when
      outputting json log record. Defaults to all log record attributes:
      http://docs.python.org/library/logging.html#logrecord-attributes
    :param timestamp: an optional string/boolean field to add a timestamp when
      outputting the json log record. If string is passed, timestamp will be added
      to log record using string as key. If True boolean is passed, timestamp key
      will be "timestamp". Defaults to False/off.
    """
    self.json_encoder = JsonEncoder
    self.json_serializer = json.dumps
    reserved_attrs = kwargs.pop("reserved_attrs", RESERVED_ATTRS)
    self.reserved_attrs = dict(zip(reserved_attrs, reserved_attrs))
    self.timestamp = kwargs.pop("timestamp", False)

    logging.Formatter.__init__(self, *args, **kwargs)

    # Parses format string looking for substitutions
    # This method is responsible for returning a list of fields (as strings) to include in all log messages.
    standard_formatters = re.compile(r'\((.+?)\)', re.IGNORECASE)
    self._required_fields = standard_formatters.findall(self._fmt)
    self._skip_fields = dict(zip(self._required_fields, self._required_fields))
    self._skip_fields.update(self.reserved_attrs)

  def format(self, record):
    """Formats a log record and serializes to json"""

    log_record = {
      "timestamp": datetime.fromtimestamp(record.created, tz=timezone.utc),
      "levelname": record.levelname,
      "logtype": "nbox-json-log-v1",
      "message": "open to find out",
      "log": {
        "code": {
          "file": record.filename,
          "line": record.lineno,
        },
      }
    }

    # message_dict = {}
    # if isinstance(record.msg, dict):
    #   message_dict = record.msg
    #   record.message = None
    # else:
    #   record.message = record.getMessage()
    # # only format time if needed
    # if "asctime" in self._required_fields:
    #   record.asctime = self.formatTime(record, self.datefmt)

    # # Display formatted exception, but allow overriding it in the
    # # user-supplied dict.
    # if record.exc_info and not message_dict.get('exc_info'):
    #   message_dict['exc_info'] = self.formatException(record.exc_info)
    # if not message_dict.get('exc_info') and record.exc_text:
    #   message_dict['exc_info'] = record.exc_text
    # # Display formatted record of stack frames
    # # default format is a string returned from :func:`traceback.print_stack`
    # try:
    #   if record.stack_info and not message_dict.get('stack_info'):
    #     message_dict['stack_info'] = self.formatStack(record.stack_info)
    # except AttributeError:
    #   # Python2.7 doesn't have stack_info.
    #   pass

    if isinstance(record.msg, dict):
      log_record["log"]["data"] = record.msg
    elif record.msg:
      log_record["log"]["message"] = record.getMessage().splitlines()

    json_str = json.dumps(
      log_record,
      cls = self.json_encoder,
      ensure_ascii = True,
      separators = (',', ':'),
    )
    return json_str
