# for interacting with eyecon api, like logging in, getting events, agent details.

import requests
# HAWK API
import hawkAPI.lib.core.SmtpSend as SmtpSend
from hawkAPI.lib.core.ThreadPool import *

from hawkAPI.lib.core.hawkcore import hawkcore
from hawkAPI.lib.core.hawkapi import hawkapi
from hawkAPI.lib.core.hawklib import hawklib

from errors import *


class eyeconAPI(object):
    def __init__(self, config):
        self.config = config

    def login(self):
        """ Login into HAWK API."""

        # authenticate and start our handler

        try:
                self.hawk = hawkcore(self.config['api_server'])
                self.hawk.logfile("/var/log/hawk/hawk-health.log")
        except Exception as e:
                errstr = 'Failure: Unable to create hawkcore object using API Server: %s' % (
                    self.config['api_server'])
                errors = getattr(e, 'errors', None)
                logger.exception(errstr)
                raise HawkCoreError(
                    errstr, errors, api_server=self.config['api_server'])
        try:
                if 'insecure' in self.config.keys() and self.config['insecure'].lower() == 'true':
                        self.hawk.SSLVerify(False)
                if 'timeout' in self.config.keys():
                        self.hawk.setTimeout(self.config['timeout'])
                if 'retry' in self.config.keys():
                        self.hawk.setRetry(self.config['retry'])
                if 'verbose' in self.config.keys() and self.config['verbose']:
                        self.hawk.debug(1)
        except Exception as e:
                errstr = 'Failure: Unable to set attributes.'
                errors = getattr(e, 'errors', None)
                logger.exception(errstr)
                raise HawkCoreError(errstr, errors)

        try:
                x = self.hawk.login(
                    self.config['api_username'], self.config['api_password'])
                if x == None:
                        raise Exception("authentication failed")
                logger.info("Authenticated with remote API successfully (%s @ %s) ..." %
                            (self.config['api_username'], self.config['api_server']))
                self.config['user_info'] = x
        except Exception as e:
                errstr = 'Failure: User %s Failed to log into API %s (%s)' % (
                    self.config['api_username'], self.config['api_server'], e)
                errors = getattr(e, 'errors', None)
                logger.exception(errstr)
                raise HawkLoginError(
                    errstr, errors, user=self.config['api_username'])

    def query_events(self, start_time=None, end_time=None, **kwargs):
        """ Query for events.
        Args:
            start_time (DATETIME): Start time for query
            end_time (DATETIME): End time for query
            **kwargs: Arbitrary keyword arguments for querying events.
        Returns:
            json: results of event query for success. False, if unsuccessful.
        """
        pass

    def query_agents(self, uuid=None, hostname=None, address=None, group=None):
        # https://portal.hawk.io:8080/API/1.1/search/agents
        """Query HAWK Agents
        List all agents, or query for specific agents.

        Example:
            self.query_agents()

        Args:
            uuid (str): Agent UUID.
            hostname (str): Agent's Hostname.
            address (str): Agent's IPv4 IP Address.
            group (str): Group Agent is located in.

        Returns:
            (list) List of dictionaries of agents.
        """

        # Query local DB first, If doesn't exist then query API.

        # Always Query all agents, and do the filter locally.

        # Save all the agents in our local database.

        # Return
'''[{
    'address': '54.202.126.194',
    'agent_id': 91,
    'agent_uuid': 'vol046af7ba7853167c1',
    'agent_version': 'v1.6.0-94504',
    'applications': [ {'install_date': '20190906', 'location': '', 'name': 'Amazon SSM Agent', 'publisher': 'Amazon Web Services', 'version': '2.3.634.0'}],
    'approved_user_id': null,
    'date_added': '2019-10-30 12:58:27',
    'date_approved': null,
    'date_updated': '2019-11-26 21:25:46',
    'group_name': 'hawk',
    'hostname': 'EC2AMAZ-S5GK1EM',
    'os': 'Microsoft Windows Server 2019 Datacenter x64 (6.3 build 17763)',
    'pending_updates': false,
    'settings': [],
    'status': true,
    'system_info': {cpu: {}, 'disk': {}, 'hostname': '', 'memory': {}, 'network': {}, 'processes': {}, 'services': [{}], 'tasks': []},
    'updates': [],
}]'''
        pass

    def agent_details(self, uuid=None):
        """Query HAWK agent for details.

        Args:
            uuid (str): Agent UUID.

        Returns:
            (dict) Agent details like network connections.
        """

        # Query API for agent details

        # Save results in DB, with cache enter datetime.

        # return lookup point (This is to simplefy the process and to limit memory usage)

        pass

    def get_playbooks(self):
        """ Get and Parse Playbooks

            Returns:
                list of playbooks
        """

        # Query playbooks
        #
