#!/usr/bin/env python
#
# This file is part of pacman-mirrors.
#
# pacman-mirrors is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pacman-mirrors is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pacman-mirrors.  If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Frede Hundewadt <echo ZmhAbWFuamFyby5vcmcK | base64 -d>

"""Pacman-Mirrors JSON Functions"""

import collections
import json


def json_dump_file(data: list, filename: str) -> None:
    with open(filename, "w") as outfile:
        json.dump(data, outfile)


def read_file_content(file_name: str, binary: bool = False) -> str:
    """
    Reads the content of a file.
    """
    mode = "rb" if binary else "r"
    with open(file_name, mode) as file:
        return file.read()


def read_json_file(filename: str, use_ordered_dict: bool = True) -> list:
    """Reads json data from file."""
    data = []  # Represent an empty JSON array
    try:
        file_content = read_file_content(filename, binary=use_ordered_dict)

        if use_ordered_dict:
            # noinspection PyTypeChecker
            data = json.loads(
                file_content.decode("utf8"),
                object_pairs_hook=collections.OrderedDict,
            )
        else:
            data = json.loads(file_content)
    except OSError:
        pass

    return data


def write_json_file(data: list, filename: str, dictionary: bool = False) -> bool:
    """Writes data to file as json
    :param data
    :param filename:
    :param dictionary:
    """
    try:
        # TODO what was the purpose of dictionary?
        if dictionary:
            with open(filename, "w") as outfile:
                json.dump(data, outfile)
        else:
            with open(filename, "w") as outfile:
                json.dump(data, outfile, sort_keys=True, indent=4)

        return True

    except OSError:
        return False
