import logging
import json
from json.decoder import JSONDecodeError
from .config import PYWAL_COLORS_PATH

def get_pywal_colors():
    """
    Fetches the Pywal colors from the cache file.

    :return: the colors generated by Pywal
    :rType: list
    """
    colors = []
    wallpaper = ''
    try:
        with open(PYWAL_COLORS_PATH, 'r') as f:
            pywal_data = json.load(f)
            if 'colors' in pywal_data:
                for key in pywal_data['colors']:
                    colors.append(pywal_data['colors'][key])
            else:
                error_message = '%s does not contain any color values' % PYWAL_COLORS_PATH
                logging.error(error_message)
                return (False, None, error_message)

            if 'wallpaper' in pywal_data:
                wallpaper = pywal_data['wallpaper']
            else:
                error_message = '%s does not contain a wallpaper path' % PYWAL_COLORS_PATH
                logging.error(error_message)
                return (False, None, error_message)

    except (IOError, JSONDecodeError):
        error_message = 'Could not read colors from: %s' % PYWAL_COLORS_PATH
        logging.error(error_message)
        return (False, None, error_message)

    if len(colors) < 16:
        error_message = '%s containing the generated Pywal colors is invalid' % PYWAL_COLORS_PATH
        logging.error(error_message)
        return (False, None, error_message)

    logging.debug('Successfully fetched Pywal colors')
    return (True, {'colors': colors, 'wallpaper': wallpaper}, None)
