#lambda pre-built imports 
import socket
import json
import datetime

#lambda external imports
import whois # python-whois 


def default(o):
    if isinstance(o, (datetime.date, datetime.datetime)):
        return o.isoformat()


def return_code(status, body):
    return {"statusCode": status,"body": json.dumps(body,sort_keys=True,
    indent=1,default=default)}

def exWhois(domain):
    try:
        result = whois.whois(domain)
        return {'code':'SUCCESS','content':result}
    except Exception as E:
        print(E)
        return {'code':'ERROR','content':E}
        

def lambda_handler(event, context):
    try:
        if event['pathParameters'] and event['pathParameters']['proxy']:
            domain = event['pathParameters']['proxy']
            result = exWhois(domain)
            if result['code'] == 'ERROR':
                return return_code(404,"domain name not found in whois records.")
            else:
                return return_code(200,(result['content']))
        else:
            return return_code(400, 'domain name or ip param must be present.')
    except Exception as E:
        print(E)
        return return_code(501, 'Internal server error')