# Copyright (C) 2020, 2021 The Meme Factory, Inc.  http://www.karlpinc.com/

# This file is part of PGWUI_Common.
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program 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
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#

# Karl O. Pinc <kop@karlpinc.com>

'''Helper routines for checking a PGWUI component's settings
'''

from ast import literal_eval

from . import exceptions


def require_settings(component, required_settings, conf):
    errors = []
    for setting in required_settings:
        if setting not in conf:
            errors.append(exceptions.MissingSettingError(
                '{}:{}'.format(component, setting)))
    return errors


def unknown_settings(component, settings, conf):
    errors = []
    for setting in conf:
        if setting not in settings:
            errors.append(exceptions.UnknownSettingKeyError(
                '{}:{}'.format(component, setting)))
    return errors


def boolean_settings(component, booleans, conf):
    errors = []
    for setting in booleans:
        if setting in conf:
            try:
                val = literal_eval(conf[setting])
            except ValueError:
                val = None
            if (val is not True
                    and val is not False):
                errors.append(exceptions.NotBooleanSettingError(
                    '{}:{}'.format(component, setting), conf[setting]))
    return errors


def boolean_choice(component, settings, conf):
    errors = []
    for setting in settings:
        if setting in conf:
            if conf[setting] not in (
                    'yes-always', 'choice-yes', 'choice-no', 'no-never'):
                errors.append(exceptions.NotBooleanChoiceSettingError(
                    f'{component}:{setting}', conf[setting]))
    return errors
