import asyncio
from typing import Optional

from databases import Database


class _DB:
    ro: Database = None
    rw: Database = None

    async def setup(self, rw_uri: str, ro_uri: Optional[str] = None, **kwargs):
        self.rw = self.rw or Database(rw_uri, **kwargs)
        self.ro = self.ro or (Database(ro_uri, **kwargs) if ro_uri else self.rw)
        await self.connect()

    @property
    def _targets(self):
        return (self.rw,) if self.ro == self.rw else (self.rw, self.ro)

    async def connect(self):
        targets = [t.connect() for t in self._targets if not t.is_connected]
        if targets:
            await asyncio.wait(targets)

    async def disconnect(self):
        targets = [t.disconnect() for t in self._targets if t.is_connected]
        if targets:
            await asyncio.wait(targets)


db = _DB()
