"""
Collection of functions to aid with some common database tasks
"""
import configparser


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def config_or_file(config_file, to_check):
    """
    A small helper function that checks if to check if to_check is a valid file
    path or an entry in the config_file (ini file). This is mainly used to
    distinguish if a potential database connection attribute is for an SQLite
    database or a section header in a config file.

    Parameters
    ----------

    config_file :`str`
        The path to the config file that we want to check
    to_check :`str`
        The potential config section header or SQLite database path

    Returns
    -------

    is_config :`bool`
        If True, then `to_check` is a config section entry if false then
        `to_check` is a valid file that exists (can be opened)

    Raises
    ------

    FileNotExistsError
        If the config file does not exist
    IOError
        This may be raised if the config file can't be opened for some reason.
        I am not 100% sure.
    ValueError
        if `to_check` is not a valid file path and not a config file section
    RuntimeError
        if `to_check` is both a valid file and a config section header
    """

    # First make sure that the file exists, this should raise a
    # FileNotExistsError if not.
    # TODO: Check if ther are any instances where an IOError will be raised
    open(config_file).close()

    # with open(config_file) as infile:
    #     for i in infile:
    #         print(i)

    # To indicate that the file is valid, i.e. exists and can be openned
    valid_file = False

    # If we get here then the config file is valid. First we check if to_check
    # is a file
    try:
        open(to_check).close()

        # If we get here make a note that the file is valid
        valid_file = True
    except (FileNotFoundError, IOError):
        # Not a valid file so now we will check if it is a section in the
        # config file
        pass

    # Now we check if the config header entry is valid
    config = configparser.ConfigParser()
    # print(config_file)
    # config.read_file(config_file)
    config.read(config_file)

    # Do we have a valid section
    valid_section = config.has_section(to_check)

    # If both are True then we raise a RuntimeError
    if valid_file is True and valid_section is True:
        raise RuntimeError("'{0}' is valid config section in '{1}' and a "
                           "valid file".format(to_check, config_file))
    elif valid_file is True:
        return False
    elif valid_section is True:
        return True
    else:
        raise ValueError("'{0}' is not a valid config section in '{1}' and not"
                         "a valid file".format(to_check, config_file))
