from django.contrib.gis.geoip2 import GeoIP2
from ipware import get_client_ip
import socket


def get_ip_and_country(request, default_country='in', default_currency='INR'):
    ip, is_routable = get_client_ip(request)
    
    if not ip:
        return '127.0.0.1', default_country, default_currency

    try:
        socket.inet_aton(ip)
        if ip.startswith(('127.', '192.168.', '10.', '172.')):
            return ip, default_country, default_currency
    except socket.error:
        return ip, default_country, default_currency

    try:
        g = GeoIP2()
        country = g.country(ip)['country_code'].lower()
        currency_map = {
            'us': 'USD',
            'eu': 'EUR',
            'gb': 'GBP',
            'in': 'INR',
            'au': 'AUD',
            'ca': 'CAD',
            'jp': 'JPY',
        }
        currency = currency_map.get(country, default_currency)
        return ip, country, currency
    except Exception:
        return ip, default_country, default_currency
    
def get_city_and_country_from_ip(ip):
    g = GeoIP2()

    tmp = {'country':'',
           'city':'',
           'latitude':'',
           'longitude':''}
    if ip!='127.0.0.1':

        try:
            # country = g.country(ip)
            city = g.city(ip)
            # print(city)
            tmp['country'] = city['country_name']
            tmp['city'] = city['city']
            tmp['latitude'] = city['latitude']
            tmp['longitude'] = city['longitude']
        except Exception as e:
            print(e)
            
    return tmp
    