import json
import requests


def select_moneymarkets(market=None, exclude_exchanges=True,
                        base_url="https://raw.githubusercontent.com/JerBouma/FinanceDatabase/"
                                 "master/Database/Moneymarkets",
                        use_local_location=False, all_moneymarkets_json="_Moneymarkets"):
    """
    Description
    ----
    Returns all moneymarkets when no input is given and has the option to give
    a specific set of symbols for the market you provide.

    Input
    ----
    market (string, default is None)
        If filled, gives all data for a specific market.
    exclude_exchanges (boolean, default is True):
        Whether you want to exclude exchanges from the search. If False,
        you will receive multiple times i.e. SOND from different exchanges.
    base_url (string, default is GitHub location)
        The possibility to enter your own location if desired.
    use_local_location (string, default False)
        The possibility to select a local location (i.e. based on Windows path)
    all_moneymarkets_json (string, default is _Moneymarkets)
        Alter the name of the all moneymarkets json if desired.

    Output
    ----
    json_data (dictionary)
        Returns a dictionary with a selection or all data based on the input.
    """
    if market:
        json_file = f"{base_url}/{market}.json"
        if use_local_location:
            with open(json_file) as json_local:
                json_data = json.load(json_local)
        else:
            try:
                request = requests.get(json_file)
                json_data = json.loads(request.text)
            except json.decoder.JSONDecodeError:
                raise ValueError(f"Not able to find any data for {market}.")
    else:
        json_file = f"{base_url}/{all_moneymarkets_json}.json"
        if use_local_location:
            with open(json_file) as json_local:
                json_data = json.load(json_local)
        else:
            try:
                request = requests.get(json_file)
                json_data = json.loads(request.text)
            except json.decoder.JSONDecodeError:
                raise ValueError("Not able to find any data.")

    if exclude_exchanges:
        for moneymarket in json_data.copy():
            if '.' in moneymarket:
                del json_data[moneymarket]
        if not len(json_data):
            raise ValueError("Because exclude_exchanges is set to True, all available data for "
                             f"this combination ({market}) is removed. Set this parameter to False to obtain data.")

    return json_data