import os

from troposphere import serverless
import troposphere as tp

def _generate_functions(functions, execution_role, conio_env, layers, subnets, security_groups, code_uri):
    # pprint.pprint(functions)
    prev_function = None
    for f in functions:
        variables = {
            'CONIO_ENV': tp.Ref(conio_env)
        }
        variables.update(f['variables'])
        kwargs = {
            "CodeUri": code_uri,
            "Handler": f['handler'],
            "FunctionName": tp.Sub("${ConioEnv}-" + f['function_name'].replace('.', '-')),
            "Description": f['description'],
            "Runtime": 'python3.8',
            "Environment": serverless.Environment(
                Variables=variables
            ),
            "Role": execution_role,  # tp.GetAtt(execution_role, "Arn"),
            "Timeout": 30,
            "VpcConfig": serverless.VPCConfig(
                SubnetIds=subnets,
                SecurityGroupIds=security_groups
            ),
            "MemorySize": 512,
            "Layers": [tp.Ref(l) for l in layers]
        }
        if os.environ.get('CONIO_ENV', 'staging') == 'staging':
            kwargs['Tracing'] = 'Active'
        # if prev_function:
        #     kwargs["DependsOn"] =  prev_function
        function = serverless.Function(
            f['name'],
            **kwargs
        )
        yield function
        prev_function = function
