import json


def set_location_properties(obj, location):
    """Helper to set location-related properties on either destinations or events.

    Events have optional related destination, which is the event location.

    :param obj: Dictionary representation of object to which to add location properties
    :param location: Destination object from which to extract location properties
    :returns: passed obj dictionary, with added properties
    """
    obj['placeID'] = location.pk if location else None
    obj['point'] = json.loads(location.point.json) if location else None
    obj['attributes'] = {
        'City': location.city if location else None,
        'Postal': location.zipcode if location else None,
        'Region': location.state if location else None,
        'StAddr': location.address if location else None
    }
    # convert to format like properties on ESRI geocoder results
    x = obj['point']['coordinates'][0] if location else None
    y = obj['point']['coordinates'][1] if location else None
    obj['extent'] = {'xmax': x, 'xmin': x, 'ymax': y, 'ymin': y}
    obj['location'] = {'x': x, 'y': y}
    return obj