import boto3
import re
import os

region = os.getenv('region')
domain_table = os.getenv('domain_table')
ip_table = os.getenv('coinblockerlist_ips')

dynamodb = boto3.resource('dynamodb', region_name=region)
coinblockerlist_domain_table = dynamodb.Table(domain_table)
coinblockerlist_ip_table = dynamodb.Table(ip_table)


def return_code(status, body):
    return {"statusCode": status, "headers": {"Content-Type": "text/plain",'Access-Control-Allow-Origin':"*"}, "body": body}


def search_domain(domain_name):
    try:
        response = coinblockerlist_domain_table.get_item(Key={'domain_name': domain_name})
        if response['ResponseMetadata']['HTTPStatusCode'] == 200 and 'Item' in response:
                return return_code(200, 'domain found in coinblockerlist.')
        else:
            return return_code(404, 'domain not found in coinblockerlist.')
    except Exception as e:
        print(e)
        return return_code(500, 'Internal server error')


def search_ip(ip):
    try:
        response = coinblockerlist_ip_table.get_item(Key={'ip': ip})
        if response['ResponseMetadata']['HTTPStatusCode'] == 200 and 'Item' in response:
                return return_code(200, 'ip found in coinblockerlist.')
        else:
            return return_code(404, 'ip not found in coinblockerlist.')
    except Exception as e:
        print(e)
        return return_code(500, 'Internal server error')


def is_ip(string):
    aa = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", string)
    if aa:
        return True
    else:
        return False


def lambda_handler(event, context):
    try:
        if event['pathParameters']['proxy']:
            if is_ip(event['pathParameters']['proxy']):
                return search_ip(event['pathParameters']['proxy'])
            else:
                return search_domain(event['pathParameters']['proxy'])
        else:
            return return_code(400, 'domain_name param must be present.')
    except Exception as e:
        print(e)
        return return_code(501, 'Internal server error')

