import inspect


def extractAndInsertBeacons(handler, fridge_stream, s_idx):
    """Extracts and returns beacon data; inserts new beacons into database.
    
    Args:
        handler: Database handler.
        s_idx: Segment index.
        fridge_stream: Fridge stream.

    Returns:
        Dictionary from beacon_id to RSSI time series.
    """
    name = inspect.stack()[0][3]
    # Find dict from addr to data.
    existing_addrs = set([v["Beacon.address"] for v in handler.get(["Beacon"])])
    addr_to_data = {}
    for (ble, stream) in fridge_stream.ble_streams.items():
        for d_idx in range(stream.numSegmentData(s_idx)):
            for beacon in stream.getData(s_idx, d_idx):
                if beacon.addr not in addr_to_data:
                    addr_to_data[beacon.addr] = []
                addr_to_data[beacon.addr].append((beacon.time_str, beacon.rssi))
    # Insert new beacons.
    new_beacons = [{"address":v} for v in set(addr_to_data.keys())-existing_addrs]
    #for beacon in new_beacons:
    #    logging.info("%s Inserting %s" % (name, beacon["addr"]))
    handler.insertMany("Beacon", new_beacons)
    # Return dict from id to data.
    addr_to_id = dict([(v["Beacon.address"], v["Beacon.id"]) for v in handler.get(["Beacon"])])
    id_to_data = {}
    for (addr, data) in addr_to_data.items():
        id_to_data[addr_to_id[addr]] = data
    return id_to_data