import logging
import json
import sys
from logging import FileHandler
from os.path import join as buildpath
import netifaces as ni
from configparser import NoOptionError, ConfigParser

COMMAND_LEVEL = 99

# add a new logging level dedicated to history
logging.addLevelName(COMMAND_LEVEL, 'COMMAND_LEVEL')


def history(self, message, *args, **kwargs):
	if self.isEnabledFor(COMMAND_LEVEL):
		self._log(COMMAND_LEVEL, message, args, **kwargs)


logging.Logger.history = history


class CommandFilter(object):
	def __init__(self, level):
		self.__level = level

	def filter(self, logRecord):
		return logRecord.levelno == self.__level


class CommandHistoryFormatter(logging.Formatter):
	def __init__(self, fmt):
		super(CommandHistoryFormatter, self).__init__(fmt)

	def format(self, record):
		config = Config()
		try:
			ip = ni.ifaddresses(config.iface)[2][0]['addr']
			record.emitter = ip
		except Exception:
			record.emitter = "unavailable"
		return super(CommandHistoryFormatter, self).format(record)


class JarvisLogger(object):

	def __init__(self, manager):
		self.logger = logging.getLogger()
		self.logger.addFilter(CommandFilter(COMMAND_LEVEL))
		formatter = CommandHistoryFormatter('[%(emitter)s] %(asctime)s :: %(message)s')

		file_handler = FileHandler(
			buildpath(
				manager.current,
				manager.config.userdir,
				'commands.log'
			),
			mode='a',
			encoding='utf-8',
			delay=0
		)
		file_handler.addFilter(CommandFilter(COMMAND_LEVEL))
		file_handler.setFormatter(formatter)
		self.logger.addHandler(file_handler)

	def register(self, command):
		self.logger.history(command)


class Config(object):

	def __init__(self):
		try:
			config = ConfigParser()
			config.read("/etc/jarvis.conf")
			self.userdir = config.get('jarvis', 'user_directory')
			self.outdir = config.get('jarvis', 'output_directory')
			self.imgdir = config.get('jarvis', 'img_directory')
			self.histfile = config.get('jarvis', 'pentests_history')
			self.tree = json.loads(config.get('jarvis', 'pentest_tree'))
			self.notes = config.get('jarvis', 'notesfiles')
			self.iface = config.get('jarvis', 'interface')
			self.editor = config.get('jarvis', 'editor')
		except NoOptionError as e:
			print(e)
			sys.exit(0)
