#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module implements the handler for state of Denon AVR receivers.

:copyright: (c) 2021 by Oliver Goetz.
:license: MIT, see LICENSE for more details.
"""

import logging
import time

from typing import Hashable, Optional

import attr

from .appcommand import AppCommandCmdParam, AppCommands
from .const import DENON_ATTR_SETATTR
from .exceptions import AvrProcessingError, AvrCommandError
from .foundation import DenonAVRFoundation, convert_string_int_bool


_LOGGER = logging.getLogger(__name__)


@attr.s(auto_attribs=True, on_setattr=DENON_ATTR_SETATTR)
class DenonAVRToneControl(DenonAVRFoundation):
    """This class implements tone control functions of Denon AVR receiver."""

    _tone_control_status: Optional[bool] = attr.ib(
        converter=attr.converters.optional(convert_string_int_bool),
        default=None)
    _tone_control_adjust: Optional[bool] = attr.ib(
        converter=attr.converters.optional(convert_string_int_bool),
        default=None)
    _bass: Optional[int] = attr.ib(
        converter=attr.converters.optional(int),
        default=None)
    _bass_level: Optional[str] = attr.ib(
        converter=attr.converters.optional(str),
        default=None)
    _treble: Optional[int] = attr.ib(
        converter=attr.converters.optional(int),
        default=None)
    _treble_level: Optional[str] = attr.ib(
        converter=attr.converters.optional(str),
        default=None)

    # Update tags for attributes
    # AppCommand.xml interface
    appcommand_attrs = {
        AppCommands.GetToneControl: None}

    def setup(self) -> None:
        """Ensure that the instance is initialized."""
        # Add tags for a potential AppCommand.xml update
        for tag in self.appcommand_attrs:
            self._device.api.add_appcommand_update_tag(tag)

        self._is_setup = True

    async def async_update(
            self,
            global_update: bool = False,
            cache_id: Optional[Hashable] = None) -> None:
        """Update volume asynchronously."""
        # Ensure instance is setup before updating
        if self._is_setup is False:
            self.setup()

        # Update state
        await self.async_update_tone_control(
            global_update=global_update, cache_id=cache_id)

    async def async_update_tone_control(
            self,
            global_update: bool = False,
            cache_id: Optional[Hashable] = None):
        """Update tone control status of device."""
        if self._device.use_avr_2016_update is True:
            await self.async_update_attrs_appcommand(
                self.appcommand_attrs, global_update=global_update,
                cache_id=cache_id, ignore_missing_response=True)