from whatap.io.data_inputx import DataInputX
from whatap.io.data_outputx import DataOutputX
from StringIO import StringIO
import socket

b = StringIO()
b.write(str(0))
b.write(str(0))
b.write(str(0))
b.write(str(0))
empty = b.getvalue()

class IPUtil(object):
    def __init__(self):
        pass

    @classmethod
    def toString(cls, ip):
        if isinstance(ip, int):
            return cls.toString(str(DataOutputX.toBytes(ip)))
        else:
            #try:
            if True:
                to_str = '%d.%d.%d.%d'%(ord(ip[0]) & 0xff, ord(ip[1]) & 0xff,
                                                  ord(ip[2]) & 0xff, ord(ip[3]) & 0xff)
                return to_str
            #except Exception, e:
            #    print 'IPUtil.toString', e
            #    return '0.0.0.0'

    @classmethod
    def toBytes(cls, ip):
        if isinstance(ip, int):
            return DataOutputX.toBytes(ip)
        elif isinstance(ip, basestring):
            if isinstance(ip, unicode):
                try:
                    ip = ip.encode('ascii')
                except UnicodeEncodeError:
                    return empty
            if not ip:
                return empty

            try:
                ss = ip.split('.')
                ss_ln = len(ss)
                if ss_ln != 4:
                    return empty

                result = StringIO()
                for s in ss:
                    result.write(chr(int(s)))
                    #result.write(str(int(s)))
                return result.getvalue()
            except Exception, e:
                print e
                return empty
        return empty

    @classmethod
    def bytesToInt(cls, ip):
        if cls.isOK(ip):
            return DataInputX.toInt(ip, 0)
        else:
            return 0
    @classmethod
    def strToInt(cls, ip):
        try:
            socket.inet_aton(ip)
            return DataInputX.toInt(cls.toBytes(ip), 0)
        except socket.error:
            pass
        try:
            ip_add = socket.gethostbyname(ip)
            return DataInputX.toInt(cls.toBytes(ip_add), 0)
        except:
            return 0
        

    @classmethod
    def isOK(cls, ip):
        return ip is not None and len(ip) == 4

    @classmethod
    def isNotLocal(cls, ip):
        return cls.isOK(ip) and (ip[0] & 0xff) != 127

    @classmethod
    def parseHexString(cls, ipport):
        words = ipport.split(":")
        parsedbytes= words[0].decode('hex')

        ipbytes= StringIO()
        ipbytes.write(parsedbytes)

        portbytes= words[1].decode('hex')
        ipbytes.write(portbytes)

        return ipbytes.getvalue()
    
