from ScoutSuite.providers.azure.facade.base import AzureFacade
from ScoutSuite.providers.azure.resources.base import AzureCompositeResources

from .database_blob_auditing_policies import DatabaseBlobAuditingPolicies
from .database_threat_detection_policies import DatabaseThreatDetectionPolicies
from .replication_links import ReplicationLinks
from .transparent_data_encryptions import TransparentDataEncryptions


class Databases(AzureCompositeResources):
    _children = [
        (DatabaseBlobAuditingPolicies, 'auditing'),
        (DatabaseThreatDetectionPolicies, 'threat_detection'),
        (ReplicationLinks, None),
        (TransparentDataEncryptions, None)
    ]

    def __init__(self, facade: AzureFacade, resource_group_name: str, server_name: str):
        super(Databases, self).__init__(facade)
        self.resource_group_name = resource_group_name
        self.server_name = server_name

    async def fetch_all(self):
        for db in await self.facade.sqldatabase.get_databases(
                self.resource_group_name, self.server_name):
            # We do not want to scan 'master' database which is auto-generated by Azure and read-only:
            if db.name == 'master':
                continue

            self[db.name] = {
                'id': db.name,
                'name': db.name
            }

        await self._fetch_children_of_all_resources(
            resources=self,
            scopes={db_id: {'resource_group_name': self.resource_group_name,
                            'server_name': self.server_name,
                            'database_name': db['name']} for (db_id, db) in self.items()}
        )
