import sys
import os
modules_paths = ['../../../modules/']
for modules_path in modules_paths:
    if os.path.exists(modules_path):
        sys.path.insert(1, modules_path)


from typing import List, Tuple, Any
from networkx import Graph

from db.entities import LocationCluster, UserClusterGraph, Cluster
from db.repository import Repository
from processing.user_graph_generator import UserGraphGenerator


repo = Repository()


def get_edges_with_weights(g: Graph) -> List[Tuple[Any, Any, int]]:
    res = []
    for e in g.edges:
        res.append((*e, g.edges[e]['weight']))
    return res


def create_graphs_for_location_clusters():
    graphs_for_clusters = []

    ug = UserGraphGenerator()
    clusters: Cluster = repo.get_location_clusters()

    for cluster in clusters:
        user_ids = [n['user'] for n in cluster.nodes]
        graph: Graph = ug.create_graph_from_nodes(user_ids)

        vertices = list(graph.nodes)
        edges = get_edges_with_weights(graph)

        cluster_graph = UserClusterGraph(vertices, edges)
        graphs_for_clusters.append(cluster_graph)

    store_graphs(graphs_for_clusters)


def store_graphs(graphs: List):
    for g in graphs:
        repo.add_user_cluster_graph(g)


if __name__ == "__main__":
    create_graphs_for_location_clusters()
