import json
from db.entities.cluster import Cluster
from typing import List, Dict
from datetime import date, datetime


class ClusterSet:
    '''
    A clusterset for an arbitrary layer containing all clusters.

    :param layer_name: The name of the layer
    :param clusters: The individual clusters
    '''

    def __init__(self, layer_name: str = None, clusters: List[Cluster] = None,
                 cluster_set_dict: Dict = None, from_db=False):
        self.layer_name = layer_name
        self.clusters = clusters

        if cluster_set_dict is not None:
            self.from_serializable_dict(cluster_set_dict, from_db)

    def to_serializable_dict(self, for_db=False) -> Dict:
        serialized_dict_clusters = [cluster.to_serializable_dict(for_db)
                                    for cluster in self.clusters]
        return {
            "layer_name": self.layer_name,
            "clusters": json.dumps(serialized_dict_clusters) if for_db else serialized_dict_clusters
        }

    def from_serializable_dict(self, cluster_set_dict: Dict, from_db=False):
        self.layer_name = cluster_set_dict["layer_name"]

        serialized_dict_clusters = json.loads(cluster_set_dict["clusters"]) \
            if from_db else cluster_set_dict["clusters"]
        self.clusters = [Cluster(cluster_dict=cluster_dict, from_db=from_db)
                         for cluster_dict in serialized_dict_clusters]

    def __repr__(self):
        return json.dumps(self.to_serializable_dict())

    def __str__(self):
        return f"ClusterSet({self.__repr__()})"
