# Copyright (c) 2011, CN-Software Ltd.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
#     1. Redistributions of source code must retain the above copyright notice,
#        this list of conditions and the following disclaimer.
#
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#
#     3. Neither the name of CN-Software Ltd. nor the names of its contributors
#        may be used to endorse or promote products derived from this software
#        without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from xml.dom import minidom
from datetime import datetime

def to_str(var):
    if var is None:
        return ''
    elif var is True:
        return '1'
    elif var is False:
        return '0'
    elif isinstance(var, datetime):
        return var.isoformat()
    else:
        try:
            return str(var)
        except UnicodeEncodeError:
            return unicode(var)

def prettify_xml(xml, encoding='utf-8', indent=''):
    return minidom.parseString(xml).toprettyxml(indent=indent, encoding=encoding)

def validate_ip(ip):
    """Makes simple IP address validation"""
    try:
        ip = str(ip)
    except Exception:
        return
    ip_list = ip.split('.')
    if len(ip_list) == 4:
        for i, item in enumerate(ip_list):
            try:
                ip_list[i] = int(item)
            except ValueError:
                return
        if max(ip_list) <= 255:
            return True

def singleton_init(cls, *args, **kwargs):
    if not hasattr(cls, '_inst'):
        cls._inst = {}
    path = args[0]
    if path not in cls._inst:
        if cls.__name__ == 'BinaryFile':
            cls._inst[path] = super(cls, cls).__new__(cls, *args, **kwargs)
        else:
            cls._inst[path] = super(cls, cls).__new__(cls)

    return cls._inst[path]

class Bunch(dict):
    def __init__(self, *args, **kwds):
        super(Bunch, self).__init__(*args, **kwds)
        self.__dict__ = self
