import datetime

from dateutil.parser import parse

from crits.core.class_mapper import class_from_id

def get_relationships(obj=None, type_=None, id_=None, analyst=None):
    """
    Get relationships for a top-level object.

    :param obj: The top-level object to get relationships for.
    :type obj: :class:`crits.core.crits_mongoengine.CritsBaseAttributes`
    :param type_: The top-level object type to get relationships for.
    :type type_: str
    :param id_: The ObjectId of the top-level object.
    :type id_: str
    :param analyst: The user requesting the relationships.
    :type analyst: str
    :returns: dict
    """

    if obj:
        return obj.sort_relationships("%s" % analyst, meta=True)
    elif type_ and id_:
        obj = class_from_id(type_, id_)
        if not obj:
            return {}
        return obj.sort_relationships("%s" % analyst, meta=True)
    else:
        return {}

def forge_relationship(type_=None, id_=None,
                       class_=None, right_type=None,
                       right_id=None, right_class=None,
                       rel_type=None, rel_date=None,
                       user=None, rel_reason="",
                       rel_confidence='unknown', get_rels=False, **kwargs):
    """
    Forge a relationship between two top-level objects.

    :param type_: The type of first top-level object to relate to.
    :type type_: str
    :param id_: The ObjectId of the first top-level object.
    :type id_: str
    :param class_: The first top-level object to relate to.
    :type class_: :class:`crits.core.crits_mongoengine.CritsBaseAttributes`
    :param right_type: The type of second top-level object to relate to.
    :type right_type: str
    :param right_id: The ObjectId of the second top-level object.
    :type right_id: str
    :param right_class: The second top-level object to relate to.
    :type right_class: :class:`crits.core.crits_mongoengine.CritsBaseAttributes`
    :param rel_type: The type of relationship.
    :type rel_type: str
    :param rel_date: The date this relationship applies.
    :type rel_date: datetime.datetime
    :param user: The user forging this relationship.
    :type user: str
    :param rel_reason: The reason for the relationship.
    :type rel_reason: str
    :param rel_confidence: The confidence of the relationship.