"""
 *
 * This file is part of rasdaman community.
 *
 * Rasdaman community is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Rasdaman community is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU  General Public License for more details.
 *
 * You should have received a copy of the GNU  General Public License
 * along with rasdaman community.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright 2003 - 2015 Peter Baumann / rasdaman GmbH.
 *
 * For more information please see <http://www.rasdaman.org>
 * or contact Peter Baumann via <baumann@rasdaman.com>.
 *
"""
# make sure all string literals are unicode
from __future__ import unicode_literals


def __encode_quote(url):
    """
    Encode " from URL
    :param str url: URL to be encoded
    """
    return url.replace('"', "%22")


def url_read_exception(url, exception_message):
    """
    Open url which could return an exception (e.g: DescribeCoverage when coverage does not exist in Petascope).
    If it returns an exception, check the exception_message is in exception, if not -> not valid.

    :param str url: the url to open
    :param str exception_message: the error message could be in the exception from the requested URL
    :return: boolean (false: if status is 200 or true if message does exist)
    """
    import urllib2, ssl
    url = __encode_quote(url)
    ret = urllib2.urlopen(url, context=ssl._create_unverified_context())
    response = ret.read()
    if ret.getcode() == 200:
        return False
    elif ret.getcode() != 200 and exception_message in response:
        return True

    # Exception message is not in response and status is not 200, so it is an error
    raise Exception("Failed opening connection to '{}'. Check that the service "
                    "is up and running.".format(url))


def is_port_in_use(port):
    """
    :param: int/str port: the port to check
    :return: True if port (int) is in use, False otherwise.
    """
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('', int(port)))
        return True
    except Exception:
        return False
    finally:
        s.close()
