from parallels.core.hosting_repository.tomcat import TomcatModel, TomcatApplicationEntity
from parallels.core.runners.base import BaseRunner
from parallels.plesk.hosting_repository.base import PleskBaseModel


class PleskTomcatModel(TomcatModel, PleskBaseModel):
    def install_application(self, subscription_name, domain_name, application_war_file):
        """Install Java (Tomcat) application from specified WAR file

        :type subscription_name: str | unicode
        :type domain_name: str | unicode
        :type application_war_file: str | unicode
        :rtype: None
        """
        with self._plesk_server.runner() as runner:
            assert isinstance(runner, BaseRunner)
            runner.execute_command(
                '{tomcat_bin} --install {application_war_file} -domain {domain} -no-restart',
                dict(
                    tomcat_bin=self._plesk_server.get_bin_util_path('tomcat'),
                    application_war_file=application_war_file,
                    domain=domain_name.encode('idna')
                )
            )

    def list_applications(self, subscription_name, domain_name):
        """List Java (Tomcat) applications installed on specified domain

        :type subscription_name: str | unicode
        :type domain_name: str | unicode
        :rtype: list[parallels.core.hosting_repository.tomcat.TomcatApplicationEntity]
        """
        applications = []
        query = """
          SELECT WebApps.name as application_name FROM domains 
            JOIN DomainServices ON DomainServices.dom_id = domains.id AND DomainServices.type = 'tomcat' 
            JOIN WebApps on WebApps.domain_service_id = DomainServices.id
            WHERE domains.name = %(domain_name)s
        """
        query_args = dict(domain_name=domain_name.encode('idna'))

        for row in self.plesk_server.query_panel_db(query, query_args):
            applications.append(TomcatApplicationEntity(
                domain_name=domain_name,
                application_name=row['application_name']
            ))

        return applications
