/*
 * Aim: to create binary tree of unique record id -> unique inventor id,
 * also to allow fast search and insertion/deletion.
 * the unique inventor id is also a const Record pointer,
 * meaning that different unique record ids may be associated with a same
 * const Record pointer that represents them.
 *
 * Algorithm: clean the uinv2count and uid2uinv tree first.
 *   For any cluster in the cCluser_Info object:
 *     For any const Record pointer p in the cluster member list:
 *       create a std::pair of (p, d), where d is the delegate
 *         (or representative) of the cluster
 *       insert the pair into uid2uinv map.
 *     End for
 *   End for
 *
 *   uinv2count is updated in the same way.
 */
void
cBlocking_Operation_By_Coauthors::build_uid2uinv_tree(const ClusterInfo & cluster) {

    uinv2count_tree.clear();
    uid2uinv_tree.clear();
    uint32_t count = 0;
    //typedef list<Cluster> cRecGroup;
    // Maybe should be RecordGroup
    typedef list<Cluster> ClusterList;

    std::cout << "Building trees: 1. Unique Record ID to Unique Inventer ID. ";
    std::cout << "2 Unique Inventer ID to Number of holding patents ........";
    std::cout << std::endl;

    map<string, ClusterList>::const_iterator p = cluster.get_cluster_map().begin();
    for (; p != cluster.get_cluster_map().end(); ++p) {

        ClusterList::const_iterator q = p->second.begin();
        for (; q != p->second.end(); ++q) {

            const Record * value = q->get_cluster_head().m_delegate;
            map<const Record *, uint32_t>::iterator pcount = uinv2count_tree.find(value);
            if (pcount == uinv2count_tree.end())
                pcount = uinv2count_tree.insert(std::pair<const Record *, uint32_t>(value, 0)).first;

            for (RecordPList::const_iterator r = q->get_fellows().begin(); r != q->get_fellows().end(); ++r) {
                const Record * key = *r;
                uid2uinv_tree.insert(std::pair<const Record * , const Record *>(key, value ));
                ++(pcount->second);
                ++count;
            }
        }
    }
    std::cout << count << " nodes has been created inside the tree." << std::endl;
}