"""Validate addons options schema."""
import voluptuous as vol

from ..const import (
    ATTR_NAME, ATTR_VERSION, ATTR_SLUG, ATTR_DESCRIPTON, ATTR_STARTUP,
    ATTR_BOOT, ATTR_MAP, ATTR_OPTIONS, ATTR_PORTS, STARTUP_ONCE, STARTUP_AFTER,
    STARTUP_BEFORE, BOOT_AUTO, BOOT_MANUAL, ATTR_SCHEMA, ATTR_IMAGE, MAP_SSL,
    MAP_CONFIG, MAP_ADDONS, MAP_BACKUP, ATTR_URL, ATTR_MAINTAINER, ATTR_ARCH,
    ARCH_ARMHF, ARCH_AARCH64, ARCH_AMD64, ARCH_I386)

V_STR = 'str'
V_INT = 'int'
V_FLOAT = 'float'
V_BOOL = 'bool'
V_EMAIL = 'email'
V_URL = 'url'

ADDON_ELEMENT = vol.In([V_STR, V_INT, V_FLOAT, V_BOOL, V_EMAIL, V_URL])

ARCH_ALL = [
    ARCH_ARMHF, ARCH_AARCH64, ARCH_AMD64, ARCH_I386
]

# pylint: disable=no-value-for-parameter
SCHEMA_ADDON_CONFIG = vol.Schema({
    vol.Required(ATTR_NAME): vol.Coerce(str),
    vol.Required(ATTR_VERSION): vol.Coerce(str),
    vol.Required(ATTR_SLUG): vol.Coerce(str),
    vol.Required(ATTR_DESCRIPTON): vol.Coerce(str),
    vol.Optional(ATTR_URL): vol.Url(),
    vol.Optional(ATTR_ARCH, default=ARCH_ALL): [vol.In(ARCH_ALL)],
    vol.Required(ATTR_STARTUP):
        vol.In([STARTUP_BEFORE, STARTUP_AFTER, STARTUP_ONCE]),
    vol.Required(ATTR_BOOT):
        vol.In([BOOT_AUTO, BOOT_MANUAL]),
    vol.Optional(ATTR_PORTS): dict,
    vol.Optional(ATTR_MAP, default=[]): [
        vol.In([MAP_CONFIG, MAP_SSL, MAP_ADDONS, MAP_BACKUP])
    ],
    vol.Required(ATTR_OPTIONS): dict,
    vol.Required(ATTR_SCHEMA): {
        vol.Coerce(str): vol.Any(ADDON_ELEMENT, [
            vol.Any(ADDON_ELEMENT, {vol.Coerce(str): ADDON_ELEMENT})
        ])
    },
    vol.Optional(ATTR_IMAGE): vol.Match(r"\w*/\w*"),
}, extra=vol.ALLOW_EXTRA)


# pylint: disable=no-value-for-parameter
SCHEMA_REPOSITORY_CONFIG = vol.Schema({
    vol.Required(ATTR_NAME): vol.Coerce(str),
    vol.Optional(ATTR_URL): vol.Url(),
    vol.Optional(ATTR_MAINTAINER): vol.Coerce(str),
}, extra=vol.ALLOW_EXTRA)


def validate_options(raw_schema):
    """Validate schema."""
    def validate(struct):
        """Create schema validator for addons options."""
        options = {}

        # read options
        for key, value in struct.items():
            if key not in raw_schema:
                raise vol.Invalid("Unknown options {}.".format(key))

            typ = raw_schema[key]
            try:
                if isinstance(typ, list):
                    # nested value
                    options[key] = _nested_validate(typ[0], value)
                else:
                    # normal value
                    options[key] = _single_validate(typ, value)
            except (IndexError, KeyError):
                raise vol.Invalid(
                    "Type error for {}.".format(key)) from None

        return options

    return validate


# pylint: disable=no-value-for-parameter
def _single_validate(typ, value):
    """Validate a single element."""
    try:
        # if required argument
        if value is None:
            raise vol.Invalid("A required argument is not set!")

        if typ == V_STR:
            return str(value)
        elif typ == V_INT:
            return int(value)
        elif typ == V_FLOAT:
            return float(value)
        elif typ == V_BOOL:
            return vol.Boolean()(value)
        elif typ == V_EMAIL:
            return vol.Email()(value)
        elif typ == V_URL:
            return vol.Url()(value)

        raise vol.Invalid("Fatal error for {}.".format(value))
    except ValueError:
        raise vol.Invalid(
            "Type {} error for {}.".format(typ, value)) from None


def _nested_validate(typ, data_list):
    """Validate nested items."""
    options = []

    for element in data_list:
        # dict list
        if isinstance(typ, dict):
            c_options = {}
            for c_key, c_value in element.items():
                if c_key not in typ:
                    raise vol.Invalid(
                        "Unknown nested options {}.".format(c_key))

                c_options[c_key] = _single_validate(typ[c_key], c_value)
            options.append(c_options)
        # normal list
        else:
            options.append(_single_validate(typ, element))

    return options

@@ -2428,24 +2428,29 @@
 yp%5B0%5D, value
+, key
 )%0A          
@@ -2554,24 +2554,29 @@
 e(typ, value
+, key
 )%0A          
@@ -2826,16 +2826,21 @@
 p, value
+, key
 ):%0A    %22
@@ -2968,17 +2968,23 @@
 nvalid(%22
-A
+Missing
  require
@@ -2989,29 +2989,33 @@
 red 
-argument is not set!%22
+option '%7B%7D'.%22.format(key)
 )%0A%0A 
@@ -3422,32 +3422,40 @@
 tal error for %7B%7D
+ type %7B%7D
 .%22.format(value)
@@ -3448,21 +3448,24 @@
 .format(
-value
+key, typ
 ))%0A    e
@@ -3532,32 +3532,40 @@
 pe %7B%7D error for 
+'%7B%7D' on 
 %7B%7D.%22.format(typ,
@@ -3570,16 +3570,21 @@
 p, value
+, key
 )) from 
@@ -3621,24 +3621,29 @@
 p, data_list
+, key
 ):%0A    %22%22%22Va
@@ -4058,24 +4058,31 @@
 ey%5D, c_value
+, c_key
 )%0A          
@@ -4201,16 +4201,21 @@
  element
+, key
 ))%0A%0A    

Update error message (#48)