from typing import List, Optional, Type

from edpdependencyinjection import DependencyContext
from dimessageprocessor import DiMessageProcessorExecutorFactory
from messagebus import SubscriptionInfo
from messageprocessor import MessageProcessorCallback
from rediseventlock import (
    EventLockCallback,
    EventLockMessageProcessorExecutor,
    TenantRedisClient,
)


class DiEventLockMessageProcessorExecutorFactory(DiMessageProcessorExecutorFactory):
    def __init__(
        self,
        dependency_context: DependencyContext,
        callback_definitions: List[Type[MessageProcessorCallback]],
        tenant_redis: TenantRedisClient,
        subscriptions: Optional[List[SubscriptionInfo]] = None,
        lock_timeout: int = 1200,
    ):
        super().__init__(
            dependency_context=dependency_context,
            callback_definitions=callback_definitions,
        )
        self.tenant_redis = tenant_redis
        self.subscriptions = subscriptions
        self.lock_timeout = lock_timeout

    def build_executor(self, message_processor):
        return EventLockMessageProcessorExecutor(
            event_processor=message_processor,
            callbacks=[
                *(
                    self.dependency_context.get_instance(callback_def)
                    for callback_def in self.callback_definitions
                ),
                EventLockCallback(
                    redis_client=self.tenant_redis,
                    subscriptions=self.subscriptions,
                    lock_timeout=self.lock_timeout,
                ),
            ],
        )
