import requests
import time
import boto3
import os


region = os.getenv('region')
domain_table = os.getenv('domain_table')
domain_changes_table = os.getenv('coinblockerlist_domains')
ip_table = os.getenv('coinblockerlist_ips')
ip_changes_table = os.getenv('coinblockerlist_ip_changes')
coinblockerlist_domain_git = 'https://gitlab.com/ZeroDot1/CoinBlockerLists/raw/master/list.txt'
coinblockerlist_ip_git =  'https://gitlab.com/ZeroDot1/CoinBlockerLists/raw/master/MiningServerIPList.txt'


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


def get_coin_blocker_domain_list():
    response = requests.get(coinblockerlist_domain_git)
    if response.status_code == 200:
        updated_coin_blocker_domain_list = response.text
        # Spliting and deleting the empty last raw from list
        updated_coin_blocker_domain_list = updated_coin_blocker_domain_list.split('\n')[:-1]
        return updated_coin_blocker_domain_list
    else:
        return False

def get_coin_blocker_ip_list():
    response = requests.get(coinblockerlist_ip_git)
    if response.status_code == 200:
        updated_coin_blocker_ip_list = response.text
        # split and deleting the empty last raw from list and the comment lists
        updated_coin_blocker_ip_list = updated_coin_blocker_ip_list.split('\n')[8:-1]
        return updated_coin_blocker_ip_list
    else:
        return False


def get_current_dynamodb_coin_blocker_domain_list():
    dynamodb_domain_list = coinblockerlist_domain_table.scan()
    new_list = []
    for i in dynamodb_domain_list['Items']:
        new_list.append(i['domain_name'])
    return new_list


def get_current_dynamodb_coin_blocker_ip_list():
    dynamodb_domain_list = coinblockerlist_ip_table.scan()
    new_list = []
    for i in dynamodb_domain_list['Items']:
        new_list.append(i['ip'])
    return new_list


def compare_current_and_updated_domain_list():
    updated_coin_blocker_domain_list = get_coin_blocker_domain_list()
    current_dynamodb_coin_blocker_domain_list = get_current_dynamodb_coin_blocker_domain_list()
    new_domains = set(updated_coin_blocker_domain_list) - set(current_dynamodb_coin_blocker_domain_list)
    if new_domains == set():
        new_domains = False
    deleted_domains = set(current_dynamodb_coin_blocker_domain_list) - set(updated_coin_blocker_domain_list)
    if deleted_domains == set():
        deleted_domains = False
    return {'new_domains': new_domains, 'deleted_domains': deleted_domains}


def compare_current_and_updated_ip_list():
    updated_coin_blocker_ip_list = get_coin_blocker_ip_list()
    current_dynamodb_coin_blocker_ip_list = get_current_dynamodb_coin_blocker_ip_list()
    new_ips = set(updated_coin_blocker_ip_list) - set(current_dynamodb_coin_blocker_ip_list)
    if new_ips == set():
        new_ips = False
    deleted_ips = set(current_dynamodb_coin_blocker_ip_list) - set(updated_coin_blocker_ip_list)
    if deleted_ips == set():
        deleted_ips = False
    return {'new_ips': new_ips, 'deleted_ips': deleted_ips}


def add_new_domains_to_dynamodb(new_domains_list):
    for domain in new_domains_list:
        coinblockerlist_domain_table.put_item(Item={'domain_name': domain})


def add_new_ips_to_dynamodb(new_ips_list):
    for ip in new_ips_list:
        coinblockerlist_ip_table.put_item(Item={'ip': ip})


def remove_deleted_domains_from_dynamodb(deleted_domains_list):
    for domain in deleted_domains_list:
        coinblockerlist_domain_table.delete_item(Key={'domain_name': domain})


def remove_deleted_ips_from_dynamodb(deleted_ips_list):
    for ip in deleted_ips_list:
        coinblockerlist_ip_table.delete_item(Key={'ip': ip})


def save_domain_changes_to_dynamodb(new_domains_list, deleted_domains_list):
    if len(new_domains_list) + len(deleted_domains_list) != 0:
        date = int(time.time())
        coin_blocker_list_domain_changes_table.put_item(Item={'date': date, 'new_domains': new_domains_list,
                                                              'deleted_domains': deleted_domains_list})
        return True
    else:
        print("No changes found.")
        return False


def save_ip_changes_to_dynamodb(new_ips_list, deleted_ips_list):
        date = int(time.time())
        coin_blocker_list_ip_changes_table.put_item(Item={'date': date, 'new_ips': new_ips_list,'deleted_ips': deleted_ips_list})
        return True
        


def update_domains():
    try:
        print("checking for changes in domain list.")
        compare_lists = compare_current_and_updated_domain_list()
        if compare_lists['new_domains']:
            add_new_domains_to_dynamodb(compare_lists['new_domains'])
        if compare_lists['deleted_domains']:
            remove_deleted_domains_from_dynamodb(compare_lists['deleted_domains'])
        if  compare_lists['new_domains'] or compare_lists['deleted_domains']:
            save_domain_changes_to_dynamodb(compare_lists['new_domains'], compare_lists['deleted_domains'])
        return True
    except Exception as e:
        print(e)
        return False


def update_ips():
    try:
        print("checking for changes in ip list.")
        compare_lists = compare_current_and_updated_ip_list()
        if compare_lists['new_ips']:
            add_new_ips_to_dynamodb(compare_lists['new_ips'])
        if compare_lists['deleted_ips']:
            remove_deleted_ips_from_dynamodb(compare_lists['deleted_ips'])
        if compare_lists['new_ips'] or compare_lists['deleted_ips']:
            save_ip_changes_to_dynamodb(compare_lists['new_ips'], compare_lists['deleted_ips'])
        return True
    except Exception as e:
        print(e)
        return False


def lambda_handler(event, context):
    print("starting coinblockerlist update.")
    if update_domains():
        print("domains update check run successfully.")
    if update_ips():
        print("ip update check run successfully.")
    print('Done')

