import sys
import os
modules_path = '../../../modules/'
if os.path.exists(modules_path):
    sys.path.insert(1, modules_path)

import json
from db.entities import Cluster
from typing import List
from db.repository import Repository

LAYER_FILES = ['User_Demand_Layer.json']

repo = Repository()


def get_clusters(layer_file) -> List[Cluster]:
    with open(layer_file, 'r') as file:
        clusters = json.loads(file.read())
        return [Cluster(cluster_dict=cluster, from_db=False) for cluster in clusters]


def store_generic_clusters(clusters: List[Cluster], layer):
    try:
        with open(f'{layer}.json', 'w') as file:
            cluster_dicts = [c.to_serializable_dict(for_db=False) for c in clusters]
            file.write(json.dumps(cluster_dicts))
    except:
        print(f"failed writing {layer}")

    try:
        for cluster in clusters:
            repo.add_cluster(cluster)
    except:
        print(f"failed uploading {layer}")


for layer in LAYER_FILES:
    clusts: List[Cluster] = get_clusters(layer)
    store_generic_clusters(clusts, layer)