from yta_editor_time.temporal_specification.abstract import TemporalSpecification
from yta_editor_time.temporal_specification.temporal_resolution import TemporalResolution


class AndTemporalSpecification(TemporalSpecification):
    """
    Special `TemporalSpecification`.

    The set of specifications provided will be resolved
    according to the evaluation context. It will be
    active only if all of the specifications are active.

    The `t_local_normalized` value used will be the one
    obtained in the last `TemporalSpecification` resolved,
    only if all of them are active.
    """

    def __init__(
        self,
        temporal_specifications: list[TemporalSpecification]
    ):
        self.temporal_specifications: list[TemporalSpecification] = list(temporal_specifications)
        """
        The list of `TemporalSpecification` instances that will
        be evaluated. All of them must be active to turn the
        final result as active.
        """

    def resolve(
        self,
        evaluation_context: 'VideoEditorEvaluationContext'
    ):
        temporal_specifications_values = []
        weight = 1.0

        for temporal_specification in self.temporal_specifications:
            temporal_result = temporal_specification.resolve(evaluation_context)

            if not temporal_result.is_active:
                return TemporalResolution(
                    is_active = False,
                    t_local_normalized = None,
                    weight = 1.0
                )
            
            # TODO: I think this condition is not needed, all
            # the actives come with the 't_local_normalized'
            if temporal_result.t_local_normalized is not None:
                temporal_specifications_values.append(temporal_result.t_local_normalized)

            weight *= temporal_result.weight

        t_local_normalized = (
            temporal_specifications_values[-1]
            if temporal_specifications_values else
            evaluation_context.t_normalized
        )

        return TemporalResolution(
            is_active = True,
            t_local_normalized = t_local_normalized,
            weight = weight
        )
