from ipaddress import ip_address, IPv4Address
from random import shuffle
from urllib.request import urlopen

from .shell import shell
from .commandparams import Param, ValidationError
from . import logger, debug, error


def get_ip_adr():
    urls = [
        'api.ipify.org',
        'api.my-ip.io/ip',
        'ident.me',
    ]
    shuffle(urls)
    for url in urls:
        try:
            with urlopen(f'https://{url}', timeout=.7) as resp:
                if resp.status==200:
                    adr = resp.read().decode().strip()
                    debug('ip adr : %s', adr)
                    return True, adr
                else:
                    error(reason = f'{url} -> {resp.status} {resp.reason}')
        except Exception as x:
            error(f'{url} ! {type(x)} {x}')
    return False, 'ERROR'


class ParamIPv4(Param):
    name = 'IPv4 adr'

    def verify(self, value):
        try:
            adr = ip_address(value)
            if not isinstance(adr, IPv4Address):
                raise ValueError
            return adr
        except ValueError:
            raise ValidationError(f'{value} is not IPv4')

