from sqlite3 import Connection
from typing import (
    Callable,
    ContextManager,
    Generic,
    Type,
    TypeVar,
)

from ._ConnectionContextManager import ConnectionContextManager

T = TypeVar('T')


class DefaultRepositoryFactory(Generic[T]):
    def __init__(
        self,
        connection_allocator: Callable[[], Connection],
        repo_type: Type[T],
    ) -> None:

        self.connection_allocator = connection_allocator
        self.repo_type = repo_type

    def build(
        self,
    ) -> ContextManager[T]:

        return ConnectionContextManager(
            connection_allocator=self.connection_allocator,
            object_creator=self._create_repository,
        )

    def _create_repository(
        self,
        conn: Connection
    ) -> T:

        return self.repo_type(conn)
