import json
import os
import sys
import time
from menmice_query import MenMiceQuery
import logging

splunkhome = os.environ['SPLUNK_HOME']
sys.path.append(os.path.join(splunkhome, 'etc', 'apps', 'Snet_check_addon', 'lib'))
from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option, validators
from solnlib import conf_manager, log

ADDON_NAME = "Snet_check_addon"

def get_account_api_key(session_key: str, account_name: str):
    cfm = conf_manager.ConfManager(
        session_key,
        ADDON_NAME,
        realm=f"__REST_CREDENTIAL__#{ADDON_NAME}#configs/conf-snet_check_addon_account",
    )
    account_conf_file = cfm.get_conf("snet_check_addon_account")
    username = account_conf_file.get(account_name).get("username")
    password = account_conf_file.get(account_name).get("password")  
    logging.info(f"User is {username}")
    return username, password


@Configuration()
class GenerateQueryCommand(GeneratingCommand):
    ip = Option(require=True)
    
    def run_query(self):
        try:
            self.logger.info("starting run_query menmice...")
            session_key = self.service.token
            self.logger.info("getting configuration menmice")
            username, password = get_account_api_key(session_key, "MenMice")
            self.logger.info("Configuration succesful menmice")
        except Exception as e:
            self.logger.debug(e, exc_info=1)
        menmice = MenMiceQuery()
        response = menmice.run_query(username, password, self.ip)
        return response


    def generate(self):
        r_json = self.run_query()
        snet = r_json['result']['range']['customProperties']['Usage']
        if snet == "SNET":
            snet = True
        else:
            snet = False
        logging.info(f"Result of the SNET is {snet}")
        result = {
            "result": snet
        }
        result.update({'_time': time.time(), '_raw': json.dumps(result)})
        yield result


dispatch(GenerateQueryCommand, sys.argv, sys.stdin, sys.stdout, __name__)