import boto3
import json
import click

class FPApig:

    def __init__(self, fp_common):
        self._fp_common = fp_common

    def find_apig_rest_api(self, lambda_name, nextToken=None):
        params = {
            'limit': 500
        }
        if(nextToken is not None):
            params['position'] = nextToken
        res = self._fp_common._apig.get_rest_apis(**params)
        matches = []
        for rest_api in res['items']:
            if(rest_api['name'] == lambda_name):
                matches.append(rest_api)

        if('position' in res.keys()):
            matches = matches + self.find_apig_rest_api(lambda_name, res['position'])
        return matches

    def check_apig_exists(self, lambda_name):
        matches = self.find_apig_rest_api(lambda_name)
        self._fp_common.debug("%s" % matches)
        matches_count = len(matches)
        if(matches_count == 0):
            return False
        else:
            return True

    def create_apig_lambda_permission(self, lambda_name, rest_api_id, qualifier='current'):
        region = self._fp_common._region
        account_id = self._fp_common._aws_account_id
        return self._fp_common._lmda.add_permission(
            FunctionName=lambda_name,
            StatementId='apigateway-lambda-execute-star-%s' % rest_api_id,
            Action='lambda:InvokeFunction',
            Principal='apigateway.amazonaws.com',
            SourceArn='arn:aws:execute-api:%(region)s:%(account_id)s:%(rest_api_id)s/*' % locals(),
            Qualifier=qualifier
        )

    def create_apig_deployment(self, rest_api_id, stage_name='prod'):
        return self._fp_common._apig.create_deployment(
            restApiId=rest_api_id,
            stageName=stage_name
        )

    def create_apig_lambda_proxy(self, lambda_name, description='Autogenerated FaasPack'):
        # create rest api
        res = self._fp_common._apig.import_rest_api(
            failOnWarnings=True,
            body=json.dumps(self.generate_proxy_swagger(lambda_name, description)).encode('utf-8')
        )
        rest_api_id = res['id']

        # add permission for apig to invoke lambda
        self.create_apig_lambda_permission(lambda_name, rest_api_id)

        # create apig deployment
        self.create_apig_deployment(rest_api_id)

    def generate_proxy_swagger(self, lambda_name, description, path='api', qualifier='current'):
        region = self._fp_common._region
        account_id = self._fp_common._aws_account_id
        proxy_path = "%s/{proxy+}" % path
        uri = "arn:aws:apigateway:%(region)s:lambda:path/2015-03-31/functions/arn:aws:lambda:%(region)s:%(account_id)s:function:%(lambda_name)s:%(qualifier)s/invocations" % locals()
        return {
            "swagger": "2.0",
            "info": {
                "version": "1.0",
                "title": lambda_name
            },
            "paths": {
                proxy_path: {
                    "x-amazon-apigateway-any-method": {
                        "description": description,
                        "produces": [
                            "application/json"
                        ],
                        "responses": {},
                        "parameters": [],
                        "x-amazon-apigateway-integration": {
                            "type": "aws_proxy",
                            "uri": uri,
                            "httpMethod": "POST",
                            "passthroughBehavior": "when_no_match"
                        }
                    }
                }
            }
        }
