

import logging
import sys
import os
import re
import json
import base64

from splunk.clilib.bundle_paths import make_splunkhome_path
from splunk import ResourceNotFound
import splunk.entity as entity
from splunk.rest import simpleRequest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from google_drive_app import rest_handler
from google_drive_app.six.moves.urllib.parse import quote_plus
from google_drive_app.six import binary_type
from google_drive_app import SERVICE_KEY_REALM, SERVICE_KEY_USERNAME

path_to_mod_input_lib = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modular_input.zip')
sys.path.insert(0, path_to_mod_input_lib)
from modular_input.secure_password import get_secure_password, get_secure_password_stanza

def setup_logger(level):
    """
    Setup a logger for the REST handler
    """

    logger = logging.getLogger('splunk.appserver.service_account_keys_rest_handler.rest_handler')
    logger.propagate = False # Prevent the log messages from being duplicated in the python.log file
    logger.setLevel(level)

    log_file_path = make_splunkhome_path(['var', 'log', 'splunk', 'service_account_keys_rest_handler.log'])
    file_handler = logging.handlers.RotatingFileHandler(log_file_path, maxBytes=25000000,
                                                        backupCount=5)

    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    return logger

logger = setup_logger(logging.DEBUG)

class ServiceAccountKeysRestHandler(rest_handler.RESTHandler):

    DEFAULT_NAMESPACE ="google_drive"
    DEFAULT_OWNER = "nobody"

    def __init__(self, command_line, command_arg):
        super(ServiceAccountKeysRestHandler, self).__init__(command_line, command_arg, logger)

    def is_file_name_valid(self, lookup_file):     
        """
        Indicate if the lookup file is valid (doesn't contain invalid characters such as "..").
        """
         
        allowed_path = re.compile("^[-A-Z0-9_ ]+([.][-A-Z0-9_ ]+)*$", re.IGNORECASE)
        
        if not allowed_path.match(lookup_file):
            return False
        else:
            return True

    def setAppAsConfigured(self, session_key):
        
        postargs = {
                    'output_mode': 'json',
                    'configured' : 'true'
        }
        
        response, _ = simpleRequest('/services/apps/local/google_drive', sessionKey=session_key, method='POST', postargs=postargs, raiseAllErrors=False)

        if response.status == 200:
            return True
        else:
            return False
 
    def setKeyForDefaultInput(self, file_name, session_key):
        
        entity_entry = self.getDefaultGoogleDriveInputEntity(session_key)
        
        entity_entry['service_account_key_file'] = file_name
        entity_entry.namespace = ServiceAccountKeysRestHandler.DEFAULT_NAMESPACE
        entity_entry.owner = ServiceAccountKeysRestHandler.DEFAULT_OWNER
        entity.setEntity(entity_entry, sessionKey=session_key)
        
        self.setAppAsConfigured(session_key)
 
    def getDefaultGoogleDriveInputEntity(self, session_key):
        return entity.getEntity('admin/conf-inputs', 'google_spreadsheet', sessionKey=session_key)

    def getKeyFileContents(self, session_key):
        default_password_entry = self.getDefaultGoogleDriveInputEntity(session_key)

        # Make sure the file name is specified in the default entry
        if 'service_account_key_file' in default_password_entry:
            file_name = default_password_entry['service_account_key_file']
            service_key_file_path = make_splunkhome_path(['etc', 'apps', 'google_drive', 'service_account_keys', file_name])
            service_key = None