from parallels.plesk.hosting_repository.base import PleskBaseModel
from parallels.core.hosting_repository.domain_alias import DomainAliasModel, DomainAliasEntity
from parallels.plesk.hosting_repository.utils.cli.domalias import DomainAliasCreateCli


class PleskDomainAliasModel(DomainAliasModel, PleskBaseModel):
    def get_list(self):
        """Retrieve list of domain aliases in target panel

        :rtype: list[parallels.core.hosting_repository.domain_alias.DomainAliasEntity]
        """
        aliases = []

        query = """
            SELECT
                domain_aliases.name AS alias_name,
                domains.name AS domain_name,
                parent_domain.name AS subscription_name
            FROM domain_aliases
            LEFT JOIN domains ON domains.id = domain_aliases.dom_id
            LEFT JOIN domains parent_domain ON parent_domain.id = domains.webspace_id
        """

        rows = self.plesk_server.query_panel_db(query)

        for row in rows:
            if row['subscription_name'] is not None:
                subscription_name = row['subscription_name']
            else:
                subscription_name = row['domain_name']

            aliases.append(DomainAliasEntity(
                name=row['alias_name'], subscription_name=subscription_name
            ))

        return aliases

    def create_from_dump(self, subscription_name, domain_alias_dump, domain_name):
        """Create domain alias in target Plesk

        :type subscription_name: str
        :type domain_alias_dump: parallels.core.dump.data_model.DomainAlias
        :type domain_name: str
        """
        command = DomainAliasCreateCli(self.plesk_cli_runner, domain_alias_dump, domain_name)
        command.run()

    def is_exists_by_subscription(self, subscription_name, domain_alias_name):
        """Check if domain alias with given name exists in target Plesk

        :type subscription_name: str
        :type domain_alias_name: str
        :rtype: bool
        """
        result = self.plesk_server.query_panel_db(
            'SELECT id FROM domain_aliases WHERE name = %(domain_alias_name)s', dict(
                domain_alias_name=domain_alias_name.encode('idna')
            )
        )
        return len(result) > 0
