# -*- coding: utf-8 -*-

"""\
© Copyright. All rights reserved.

This module holds constants needed for primordial.

"""

from __future__ import unicode_literals
try:
    import fcntl
except ImportError as _:
    pass
import ipaddress
import struct
import socket
import six

try:
    from socket import SocketKind  # pylint: disable=no-name-in-module
    SOCK_STREAM = SocketKind.SOCK_STREAM
    SOCK_DGRAM = SocketKind.SOCK_DGRAM
except Exception as _:  # pylint: disable=broad-except
    SOCK_STREAM = socket.SOCK_STREAM
    SOCK_DGRAM = socket.SOCK_DGRAM


CANONICAL_TIMESTRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
CANONICAL_TIMESTRING_FORMAT_NO_ZULU = '%Y-%m-%dT%H:%M:%S.%f'
CANONICAL_TIMESTRING_FORMAT_NO_MICROSECONDS = '%Y-%m-%dT%H:%M:%SZ'


def getIP():
    try:
        ips = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")]
        if ips:
            for ip in ips:
                if ipaddress.ip_address(six.text_type(ip)).is_private:
                    return ip
            return ips[0]
    except socket.gaierror:
        pass

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ipstr = struct.pack('256s'.encode('ascii'), 'eth0'.encode('ascii'))
        return socket.inet_ntoa(
            fcntl.ioctl(s.fileno(), 0x8915, ipstr)[20:24])
    except (IOError, RuntimeError, socket.gaierror):
        return '127.0.0.1'


IP = getIP()
