import boto3
from .contexts import Contexts
from .logger import Logger

session = boto3.session.Session()
ssm = session.client(
    service_name='ssm',
)

def load_ssm_path(parameters, path, parameter_type, prefix=None, decrypt=False, recurisve=True):
    p = ssm.get_paginator('get_parameters_by_path')
    paginator = p.paginate(Path=path, Recursive=recurisve,  WithDecryption=decrypt, ParameterFilters=[{'Key': 'Type','Values': parameter_type}]).build_full_result()
    for parameter in paginator['Parameters']:
        key = parameter['Name'][len(path)+1:]
        if key in parameters:
            Logger.warn("Inherited parameter '{0}' overridden.".format(key))
        
        parameters[key] = {'Value': parameter['Value'], 
                            'Scope': Contexts.translate_context(*Contexts.decode_context_path(parameter['Name'][len(prefix):])[0:3]),
                            'Path': parameter['Name'],
                            'Version': parameter['Version'],
                            'Date': parameter['LastModifiedDate'].strftime('%Y/%m/%d-%H:%M:%S'),
                        }
    return parameters

def load_ssm_parameters(project, application, stage, parameter_type, prefix=None, uninherited=False):
    ### construct search path in hierachy with no key specified
    paths = Contexts.get_hierachy_context_paths(project, application, stage, key=None, prefix=prefix, allow_stages=(not stage is None), uninherited=uninherited)
    # Logger.debug(f"SSM paths to search in order: {paths}")
    parameters = {}
    for path in paths:
        Logger.debug(f"Loading SSM parameters: path={path}")
        load_ssm_path(parameters, path, parameter_type, prefix)
    return parameters

def locate_ssm_parameter_in_context_hierachy(project, application, stage, key, prefix=None, uninherited=False):
    paths = list(reversed(Contexts.get_hierachy_context_paths(project, application, stage, key, prefix=prefix, allow_stages=(not stage is None), uninherited=uninherited)))
    # Logger.debug(f"SSM paths to search in order: {paths}")
    for path in paths:
        Logger.debug(f"Describing SSM parameters: path={path}")
        response = ssm.describe_parameters(ParameterFilters=[{'Key':'Name', 'Values':[path]}])
        if len(response['Parameters']) > 0: return response['Parameters']
    return []
    