

import os
import sys
import json

from hawkSoar.common.logger import get_logger
from hawkSoar.common.process import ExceptionSafeProcess
from hawkSoar.plugins.base import BasePlugin
from hawkSoar.lib.query_parser import QueryInterpreter


class MatchPlugin(BasePlugin):

    ID = 'match'
    NAME = 'Match'
    DESCRIPTION = 'Match data using provided query'
    TYPE = 'match'
    DEPENDENCIES = []
    VERSION = '1.0.0'
    MODULE = 'playbook.match.Match'
    ENABLED = True
    Exceptions = []
    playbookCache = {}

    def __init__(self, plugin_administrator, config=None):
        super().__init__(plugin_administrator, config=config, plugin_path=__file__)
        self.config = config
        self.logger = get_logger()
        self.playbookCache = {}

    def process_task(self, task):
        # self.logger.debug("MATCH TASK RECEIVED: %s" % task['cmd'] )
        # self.logger.debug(json.dumps(task))
        if task['cmd'] == 'addPlaybookStep':
            self._add_playbook_step(task['data'])
            # start up new worker when new task arrives.

            if not task['data']['id'] in self.playbookCache:
                self.playbookCache[task['data']['id']] = {}

            self.logger.debug("MATCH NEW STEP TASK")
            self.logger.debug(task['data']['step'])
            self.playbookCache[task['data']['id']][task['data']['step']['id']] = {
                'matcher': QueryInterpreter(task['data']['step']['comparison']),
                'config':  task['data']['step']
            }

        else:
            # do the work
            #self.logger.debug("MATCH TASK")
            # self.logger.debug(task)
            task['data']['data']['artifacts'].append(
                {"plugin_id": self.ID, "name": "version", "module": self.MODULE, "type": "app.version",  "value": self.VERSION})
            try:
                task['data']['data']['return_value'] = self.playbookCache[task['data']
                                                                          ['playbookId']][task['data']['step']]['matcher'].compare(task['data']['data'])
            except Exception as e:
                print("Missing key?")
                print(e)
                print(self.playbookCache[task['data']['playbookId']])
                print(task['data']['step'])

            if task['data']['data']['return_value']:
                step = self.get_step_by_id(
                    task['data']['playbookId'], task['data']['step'])
                if 'tags' in step:
                    for tag in step['tags']:
                        if tag not in task['data']['data']['tags']:
                            task['data']['data']['tags'].append(tag)

            task['route'] = 'publish'

            task['data']['step'] = self.playbookCache[task['data']
                                                      ['playbookId']][task['data']['step']]['config']['next']

            # self.logger.debug("OUTGOING MATCH TASK")
            # self.logger.debug(json.dumps(task))

            self.outgoing_queue.put(task)

    def add_exception(self, msg):
        self.Exceptions.append(msg)

    def check_exceptions(self):
        # if exceptiosn found, then log out
        return self.Exceptions

    def shutdown(self):
        # stop all on-going workers here
        self.logger.debug('Match plugin is now shutting down.')

        # super().shutdown()
        self.logger.debug('Match shutdown complete.')
