from parallels.core.utils.common import cached
from parallels.plesk.source.plesk.shallow_dump.model.base.client import Client
from parallels.plesk.source.plesk.shallow_dump.model.base.domain import Domain
from parallels.plesk.source.plesk.shallow_dump.model.base.template import Template
from parallels.plesk.source.plesk.shallow_dump.model.plesk_base import PleskShallowDumpModel


class Plesk8And9CommonShallowDumpModel(PleskShallowDumpModel):
    """Common method of shallow dump obejct for source Plesk 8 and source Plesk 9"""
    @property
    @cached
    def domains(self):
        return [
            Domain(name=data['name'], owner_id=data['cl_id'])
            for data in self._dump_agent.execute_sql("SELECT displayName AS name, cl_id FROM domains")
        ]

    @property
    @cached
    def templates(self):
        query_results = self._dump_agent.execute_sql("""
            SELECT Templates.id, name FROM Templates
                JOIN Repository ON
                    Repository.component_id = Templates.id
                    AND Repository.rep_id = (SELECT val FROM misc WHERE param = 'dom_tmpl_list_id')
        """)
        return [
            Template(template_id=data['id'], name=data['name'], template_type=Template.TEMPLATE_TYPE_DOMAIN)
            for data in query_results
        ]

    @property
    @cached
    def subscription_id_to_plan_ids(self):
        return {}


class Plesk8ShallowDumpModel(Plesk8And9CommonShallowDumpModel):
    """Shallow dump object for source Plesk 8.6 panel"""
    @property
    @cached
    def clients(self):
        return [
            Client(client_id=data['id'], login=data['login'], contact_name=data['pname'])
            for data in self._dump_agent.execute_sql("SELECT id, login, pname FROM clients")
        ]

    @property
    def resellers(self):
        return []