from parallels.core.hosting_repository.panel_user import PanelUserModel
from parallels.plesk.hosting_repository.base import PleskBaseModel
from parallels.plesk.hosting_repository.utils.cli.user import UserCreateCli


class PleskPanelUserModel(PanelUserModel, PleskBaseModel):
    def create(self, user, owner):
        """Create auxiliary user in target Plesk

        :type user: parallels.core.target_data_model.AuxiliaryUser
        :type owner: parallels.core.target_data_model.Client | parallels.core.target_data_model.Reseller
        """
        command = UserCreateCli(self.plesk_cli_runner, user, owner)
        command.run()

    def is_exists(self, panel_user_username, owner_username):
        """Check if panel user with given username and owner exists in target Plesk

        :type panel_user_username: str
        :type owner_username: str
        :rtype: bool
        """
        if owner_username is None:
            owner_username = 'admin'
        result = self.plesk_server.query_panel_db(
            """
                SELECT smb_users.id FROM smb_users
                JOIN clients ON smb_users.ownerId = clients.id
                WHERE smb_users.login = %(panel_user_username)s and clients.login = %(owner_username)s
            """,
            dict(
                panel_user_username=panel_user_username,
                owner_username=owner_username
            )
        )
        return len(result) > 0
