from hypertube.core.handler.HandlerDictionary import handler_dict
from hypertube.utils.Command import Command
from hypertube.utils.CommandType import CommandType


class AbstractHandler:
    _required_parameters_count = 0

    def process(self, command):
        raise NotImplementedError('subclasses must override process()!')

    def handle_command(self, command):
        if command.command_type != CommandType.Optimize:
            self._iterate(command)

        return self.process(command)

    @staticmethod
    def validate(command, required_parameters_count, caller_type_name):
        if command.payload is None:
            raise ValueError(f"{caller_type_name} parameters mismatch")

        has_too_few_parameters = len(command.payload) < required_parameters_count
        if has_too_few_parameters:
            raise ValueError(f"{caller_type_name} parameters mismatch")

    @staticmethod
    def _iterate(command):
        for i in range(0, len(command.payload)):
            if isinstance(command.payload[i], Command):
                inner_command = command.payload[i]
                command.payload[i] = handler_dict.get(inner_command.command_type).handle_command(inner_command)
