import copy
import collections


def get_db_data(relation_data, unprefixed):
    """Organize database requests into a collections.OrderedDict

    :param relation_data: shared-db relation data
    :type relation_data: dict
    :param unprefixed: Prefix to use for requests without a prefix. This should
                       be unique for each side of the relation to avoid
                       conflicts.
    :type unprefixed: str
    :returns: Order dict of databases and users
    :rtype: collections.OrderedDict
    """
    # Deep copy to avoid unintentionally changing relation data
    settings = copy.deepcopy(relation_data)
    databases = collections.OrderedDict()

    # Clear non-db related elements
    if "egress-subnets" in settings.keys():
        settings.pop("egress-subnets")
    if "ingress-address" in settings.keys():
        settings.pop("ingress-address")
    if "private-address" in settings.keys():
        settings.pop("private-address")

    singleset = {"database", "username", "hostname"}
    if singleset.issubset(settings):
        settings["{}_{}".format(unprefixed, "hostname")] = (
            settings["hostname"])
        settings.pop("hostname")
        settings["{}_{}".format(unprefixed, "database")] = (
            settings["database"])
        settings.pop("database")
        settings["{}_{}".format(unprefixed, "username")] = (
            settings["username"])
        settings.pop("username")

    for k, v in settings.items():
        db = k.split("_")[0]
        x = "_".join(k.split("_")[1:])
        if db not in databases:
            databases[db] = collections.OrderedDict()
        databases[db][x] = v

    return databases