import os, json, jmespath
from yac.lib.paths import get_config_path
from yac.lib.registry import set_remote_string_w_challenge, get_remote_value, get_registry_keys
from yac.lib.registry import set_local_value, get_local_value, clear_entry_w_challenge
from yac.lib.validator import validate_dictionary
from yac.lib.file_converter import convert_local_files, find_and_delete_remotes
from yac.lib.variables import get_variable, set_variable
from yac.lib.file import get_file_contents, create_customization_file

YAC_VPC_SUFFIX="-vpc"

REQUIRED_FIELDS=["prefs-name.value",
                 "vpc-params"]

SUPPORTED_KEYS=[ "prefs-name",
                 "vpc-inputs",
                 "vpc-params",
                 "resource-namer"]

def validate_vpc_prefs(vpc_prefs):

    return validate_dictionary(vpc_prefs, SUPPORTED_KEYS, REQUIRED_FIELDS)

def get_vpc_prefs():

    vpc_preferences = get_local_value('vpc_preferences')

    return vpc_preferences

def set_vpc_prefs(vpc_prefs):

    if vpc_prefs:

        # save vpc preferences to local db
        set_local_value('vpc_preferences',vpc_prefs)

def clear_vpc_prefs():

    set_local_value('vpc_preferences',{})

# register namer into yac registry
def register_vpc_prefs(vpc_prefs_key, vpc_prefs_file, challenge):

    with open(vpc_prefs_file) as vpc_prefs_file_fp:

        vpc_preferences_str = vpc_prefs_file_fp.read()

        vpc_prefs_file_path = os.path.dirname(vpc_prefs_file)

        updated_vpc_preferences_str = convert_local_files(vpc_prefs_key,
                                          vpc_preferences_str,
                                          vpc_prefs_file_path,
                                          challenge)

        # add the suffix to distinguish this key as a vpc preferences key
        vpc_prefs_registry_key = vpc_prefs_key + YAC_VPC_SUFFIX

        # set the vpc defs in the registry
        set_remote_string_w_challenge(vpc_prefs_registry_key, updated_vpc_preferences_str, challenge)

def clear_vpc_prefs_from_registry(vpc_prefs_name, challenge):

    # if vpc preferences are in fact registered
    vpc_prefs = get_vpc_prefs_from_registry(vpc_prefs_name)
    
    if vpc_prefs:

        # add the suffix to distinguish this key as a vpc preferences key
        vpc_prefs_registry_key = vpc_prefs_name + YAC_VPC_SUFFIX

        # clear the vpc defs from the registry
        clear_entry_w_challenge(vpc_prefs_registry_key, challenge)

        # clear any files referenced 
        find_and_delete_remotes(vpc_prefs, challenge) 

def get_vpc_prefs_from_file(prefs_file_path):

    vpc_prefs = {}
    vpc_prefs_name = ""

    with open(prefs_file_path) as vpc_prefs_file_fp:

        vpc_prefs = json.load(vpc_prefs_file_fp)

    return vpc_prefs

def get_vpc_prefs_from_registry(vpc_def_registry_key):

    vpc_prefs = {}

    if vpc_def_registry_key:

        # get vpc defs from registry
        vpc_prefs_str = get_remote_value('%s-vpc'%vpc_def_registry_key)

        if vpc_prefs_str:
            # convert back to dictionary
            vpc_prefs = json.loads(vpc_prefs_str)

    return vpc_prefs

def get_all_vpc_def_keys():

    vpc_prefs = []

    # get all registry keys
    registry_keys = get_registry_keys()

    # find all keys with -vpc suffix
    for key in registry_keys:

        if '-vpc' in key:
            # remove the naming part
            vpc_prefs = vpc_prefs + [key.replace('-vpc','')]

    return vpc_prefs  

# vpc prefs may references a vpc-inputs script. If the script references is 
# pathed relative to the vpc prefs file, than we need to save it
# under the yac sources customization dir so it can be executed against
# any scriptfile.
def get_vpc_prefs_from_file_local_inputs(vpc_prefs_file):

    vpc_prefs = get_vpc_prefs_from_file(vpc_prefs_file)

    vpc_prefs_name = get_variable(vpc_prefs,'prefs-name',"")

    prefs_path = os.path.dirname(vpc_prefs_file)

    # see an input file is specified
    vpc_inputs = get_variable(vpc_prefs,'vpc-inputs',"")
    
    if vpc_inputs:

        inputs_contents = get_file_contents(os.path.join(prefs_path,vpc_inputs))

        # save the file under yac/lib/customizations
        script_file_yac_path = create_customization_file(vpc_prefs_name,vpc_inputs,inputs_contents)

        # change file reference so that instrincs recognizes it as part of the yac sources
        set_variable(vpc_prefs,'vpc-inputs',script_file_yac_path)

    # see if a namer is specified
    vpc_namer = get_variable(vpc_prefs,'resource-namer',"")

    if vpc_namer:

        namer_contents = get_file_contents(os.path.join(prefs_path,vpc_namer))

        # save the file under yac/lib/customizations
        namer_file_yac_path = create_customization_file(vpc_prefs_name,vpc_namer,namer_contents)

        # change file reference so that instrincs recognizes it as part of the yac sources
        set_variable(vpc_prefs,'resource-namer',namer_file_yac_path)

    return vpc_prefs                      