#!python
import base64
import codecs
import csv
import io
import os
import sys
import zipfile
from collections import namedtuple

import iptools
import requests

IP_VERSION = {'ipv4': 'IPv4', 'ipv6': 'IPv6'}
# Include or Exclude
ei_action = None


def error(text):
    sys.stderr.write(text + "\n")
    exit()


def join_data(ip, city_dict):
    jd = namedtuple(
        'MMJoinedInfo',
        (Block_IP._fields + CityLocations._fields[1:])
    )
    return [
        jd._make(x + city_dict[x.geoname_id][1:])
        for x in ip if x.geoname_id
    ]


args = sys.argv[1:]
if len(args) < 3:
    error(
        "\nUsage:python3 Ip-maxmind.py language ip_ver path [filter]\n"
        "\nExample:python3 Ip-maxmind.py ru ipv4 /full/path/to/file.txt"
        "\n\nExample:python3 Ip-maxmind.py ru ipv4 "
        "/full/path/to/file.txt include RU UA BY")

language = args[0]
filename = args[2]

if len(args) > 3:
    if args[3] != 'include' and args[3] != 'exclude':
        error('4rd argument must be a include or exclude, not ' + args[3])
    if len(args) <= 4:
        error('nothing to ' + args[3])
    else:
        ei_action = args[3]
        iso_codes = args[4:]  # for include or exclude

if args[1].lower() in IP_VERSION:
    ipver = IP_VERSION[args[1].lower()]
else:
    error('ip_version can be ipv4 or ipv6 not ' + args[1])


archive = requests.get(
    'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City-CSV.zip'
)


with zipfile.ZipFile(io.BytesIO(archive.content)) as ziped_data:
    # get parent folder name
    zip_name = ziped_data.namelist()[0].split('/')[0]

    # get list of available csv languages
    available_languages = [
        x.replace('GeoLite2-City-Locations-', '')
         .replace('.csv', '')
         .replace(zip_name + '/', '')
        for x in ziped_data.namelist()
        if 'GeoLite2-City-Locations' in x
    ]
    if language not in available_languages:
        error('Unsuported language:' + language)

    city_locations_zip = os.path.join(
        zip_name, 'GeoLite2-City-Locations-' + language + '.csv')
    with ziped_data.open(city_locations_zip) as zip_city_locations:
        csv_city_locations = csv.reader(
            codecs.iterdecode(zip_city_locations, 'utf-8'), delimiter=',')
        # field names from 1st row of csv file
        CityLocations = namedtuple('CityLocations', next(csv_city_locations))
        city_locations = {
            x[0]: CityLocations._make(x) for x in csv_city_locations
        }

    ip_block_zip = os.path.join(
        zip_name, 'GeoLite2-City-Blocks-' + ipver + '.csv')
    with ziped_data.open(ip_block_zip) as zip_blocks:
        city_blocks = csv.reader(
            codecs.iterdecode(zip_blocks, 'utf-8'), delimiter=',')
        # field names from 1st row of csv file
        Block_IP = namedtuple('Block_' + ipver, next(city_blocks))
        ip_blocks = map(Block_IP._make, city_blocks)
        data_set = join_data(ip_blocks, city_locations)


try:
    os.makedirs(os.path.dirname(filename), exist_ok=True)
except:
    print("Output path name is relative, write to current dir")


def get_ip_range(network, ipver):
    if ipver == 'IPv4':
        network = "-".join(map(str, iptools.ipv4.cidr2block(network)))
    return network


def check_fields(element, ipver, ei_action):
    try:
        if not element.network:
            return False
        network = get_ip_range(element.network, ipver)
        if network and element.city_name:
            if ei_action == "include":
                return element.country_iso_code in iso_codes
            elif ei_action == "exclude":
                return element.country_iso_code not in iso_codes
            else:
                return True
        return False
    except:
        print(element)
        return False


def encode_city(city_name):
    return base64.b64encode(bytes(city_name, 'utf-8')).decode('utf-8')


with open(filename, 'w') as file:
    for data in data_set:
        if not check_fields(data, ipver, ei_action):
            continue
        file.write(
            "%s %s;\n" % (
                get_ip_range(data.network, ipver), encode_city(data.city_name)
            )
        )
