import json
import importlib


def load_mesh(file_name):
    """Load discretize mesh saved to json file.

    For a discretize mesh that has been converted to dictionary and
    written to a json file, the function **load_mesh** loads the
    json file and reconstructs the mesh object.

    Parameters
    ----------
    file_name : str
        Name of the json file being read in. Contains all information required to
        reconstruct the mesh.

    Returns
    -------
    discretize.base.BaseMesh
        A discretize mesh defined by the class and parameters stored in the json file
    """
    with open(file_name, "r") as outfile:
        jsondict = json.load(outfile)
        module_name = jsondict.pop(
            "__module__", "discretize"
        )  # default to loading from discretize
        class_name = jsondict.pop("__class__")
        mod = importlib.import_module(module_name)
        cls = getattr(mod, class_name)
        if "_n" in jsondict:
            jsondict["shape_cells"] = jsondict.pop(
                "_n"
            )  # need to catch this old _n property here
        data = cls(**jsondict)
    return data