#!/usr/bin/python2

# Copyright (C) 2015 Red Hat
#
# This file is part of fedfind.
#
# fedfind 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.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Adam Williamson <awilliam@redhat.com>

"""Miscellaneous small functions that don't need to be class methods."""

import datetime
import os
# Upstream docs recommend using subprocess32 if possible, but make
# this optional as it's not available in EPEL.
try:
    import subprocess32 as subprocess
except ImportError:
    import subprocess
import urllib2

from urlparse import urlparse

def date_check(value, fail_raise=True):
    """Checks whether a value is a date in YYYYMMDD format, and
    returns it as a datetime.datetime instance if so. If raise is set,
    will raise an exception on failure, otherwise returns False. Will
    tolerate ints by forcing them to str.
    """
    try:
        date = datetime.datetime.strptime(str(value), '%Y%m%d')
        return date
    except ValueError:
        if fail_raise:
            err = "{0} is not a valid date in YYYYMMDD format.".format(value)
            raise ValueError(err)
        else:
            return False

def url_exists(url):
    """Checks whether a URL exists, by trying to open it."""
    scheme = urlparse(url).scheme
    if 'http' in scheme:
        try:
            urllib2.urlopen(url)
            return True
        except (ValueError, urllib2.URLError, urllib2.HTTPError):
            return False
    elif 'rsync' in scheme:
        null = open(os.devnull)
        args = ('/usr/bin/rsync', url)
        # Doesn't use check_output as it's not in Python 2.6
        process = subprocess.Popen(args, stdout=null, stderr=null)
        process.communicate()
        retcode = process.poll()
        if retcode:
            return False
        return True

def comma_list(string):
    """Split a comma-separated list of values into a list (used by the
    CLI for passing query parameters etc).
    """
    return string.split(',')

def ci_match(val1, val2, exact, neg):
    """Case-insensitive match, handles either term being false-y. More
    or less expects strings; forces both values to str() to do the
    comparison so it tolerates ints (though it matches them like
    strings). Used by the query stuff.
    """
    if not val1 and not val2:
        ret = True
    elif not val1 or not val2:
        ret = False
    elif exact:
        ret = str(val1).lower() == str(val2).lower()
    else:
        ret = str(val1).lower() in str(val2).lower()
    if neg:
        ret = not ret
    return ret
