import json

from flyers import files


def to_json_str(d: dict, pretty: bool = False):
    if pretty:
        return json.dumps(d, indent=4)
    else:
        return json.dumps(d)


def to_json_file(d: dict, filename: str, pretty: bool = False):
    json_str = to_json_str(d, pretty)
    files.write_file(filename, json_str)


def from_file(filename: str):
    return from_json_str(files.read_file(filename))


def from_json_str(s: str, c=None):
    if not c:
        return json.loads(s)
    else:
        try:
            obj = c()
        except TypeError as e:
            raise Exception("Cannot initialize object '{}'".format(c.__name__), e)
        data = json.loads(s)
        for key in obj.__dict__.keys():
            setattr(obj, key, data[key])
        return obj


class JsonSerializable(object):

    def to_json_str(self):
        return json.dumps(self, default=lambda obj: obj.__dict__)

    @classmethod
    def from_json_str(cls, json_str):
        return from_json_str(json_str, cls)

    def __str__(self):
        return self.to_json_str()
