""" Service to set covers half open"""
import logging
import voluptuous as vol

from homeassistant.components.cover import DOMAIN as COVER_DOMAIN, ATTR_POSITION
from homeassistant.const import SERVICE_SET_COVER_POSITION, ATTR_ENTITY_ID

# The domain of your component. Should be equal to the name of your component.
from homeassistant.helpers.service import async_extract_entity_ids

DOMAIN = "cover_half"

# List of component names (string) your component depends upon.
# We depend on group because group will be loaded after all the components that
# initialize devices have been setup.
DEPENDENCIES = ['group', 'cover']

# Name of the service that we expose.
SERVICE_SET_HALF = 'set_half'

ATTR_HALF_POSITION = 'half_position'

# Shortcut for the logger
_LOGGER = logging.getLogger(__name__)

# Validate that all required config options are given.
CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({})
}, extra=vol.ALLOW_EXTRA)


async def async_setup(hass, config):
    """Setup example component."""

    async def async_set_half_service(service):
        entity_ids = await async_extract_entity_ids(hass, service, expand_group=True)
        for entity_id in entity_ids:
            data = {
                ATTR_ENTITY_ID: entity_id,
                ATTR_POSITION: hass.states.get(entity_id).attributes.get(ATTR_HALF_POSITION, 20)
            }
            await hass.services.async_call(COVER_DOMAIN, SERVICE_SET_COVER_POSITION, data)

    hass.services.async_register(DOMAIN, SERVICE_SET_HALF, async_set_half_service)
    return True
