import json
from typing import List, Dict
from datetime import date, datetime


class Cluster:
    '''
    A cluster for an arbitrary layer containing some nodes.

    :param layer_name: The name of the layer in which the cluster is located
    :param cluster_label: The label of the cluster unique for the layer
    :param nodes: The individual nodes of the cluster
    '''

    def __init__(self, layer_name: str = None, cluster_label: int = None, nodes: List[Dict] = None,
                 cluster_dict: Dict = None, from_db=False):
        self.layer_name = layer_name
        self.cluster_label = cluster_label
        self.nodes = nodes

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

    def to_serializable_dict(self, for_db=False) -> Dict:
        return {
            "layer_name": self.layer_name,
            "cluster_label": self.cluster_label,
            "nodes": json.dumps(self.nodes) if for_db else self.nodes
        }

    def from_serializable_dict(self, cluster_dict: Dict, from_db=False):
        self.layer_name = cluster_dict["layer_name"]
        self.cluster_label = cluster_dict["cluster_label"]
        self.nodes = json.loads(cluster_dict["nodes"]) \
            if from_db else cluster_dict["nodes"]

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

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