import os
import json

from parallels.core.logging import get_logger
from parallels.core.utils.common import open_no_inherit

logger = get_logger(__name__)


def encode_json(data, encoder=None, pretty_print=False):
    """Convert data into json using given encoder or default one

    :type data: object
    :type encoder: json.JSONEncoder | None
    :rtype: str
    """
    if pretty_print:
        kwargs = {'sort_keys': True, 'indent': 4}
    else:
        kwargs = {}

    return json.dumps(data, cls=encoder, **kwargs)


def decode_json(data, decoder=None):
    """Convert json encoded data into python object using given decoder or default one

    :type data: str
    :type decoder: json.JSONDecoder | None
    :rtype: object
    """
    return json.loads(data, cls=decoder)


def read_json(filename):
    if not os.path.exists(filename):
        return None
    with open_no_inherit(filename, 'r') as dump_file:
        return json.load(dump_file)


def write_json(filename, data, encoder=None, pretty_print=False):
    with open_no_inherit(filename, 'w') as dump_file:
        if pretty_print:
            kwargs = {'sort_keys': True, 'indent': 4}
        else:
            kwargs = {}
        json.dump(data, dump_file, cls=encoder, **kwargs)
