from parallels.core.hosting_repository.customer import CustomerModel
from parallels.core.utils.common import join_nonempty_strs
from parallels.plesk.hosting_repository.customer import PleskCustomerModel
from parallels.plesk.utils.xml_rpc.plesk.operator import CustomerOperator, CustomerAddGenInfo, CustomerAddInfo
from parallels.plesk_multi_server.hosting_repository.base import PleskMultiServerBaseModel


class PleskMultiServerCustomerModel(CustomerModel, PleskMultiServerBaseModel):
    def get_list(self, filter_username=None):
        """Retrieve list of customers in target panel by given filter

        :type filter_username: list[str]
        :rtype: list[parallels.core.hosting_repository.customer.CustomerEntity]
        """
        return PleskCustomerModel(self.pms_management_server).get_list(filter_username)

    def disable_by_username(self, username):
        """Disable customer with given username in target panel

        :type username: str
        """
        return PleskCustomerModel(self.pms_management_server).disable_by_username(username)

    def set_external_id(self, username, external_id):
        """Set External ID for given customer in target panel

        :type username: str
        :type external_id: str
        """
        return PleskCustomerModel(self.pms_management_server).set_external_id(username, external_id)

    def create(self, owner_username, customer):
        """Create given customer in target panel; return id of created customer and list of detected errors

        :type owner_username: str | unicode | None
        :type customer: parallels.core.target_data_model.Client
        :rtype: int, list[str]
        """
        result = self.pms_management_server.plesk_multi_server_api().send_multi_server(
            CustomerOperator.Add(CustomerAddInfo(
                gen_info=CustomerAddGenInfo(
                    login=customer.login,
                    passwd=customer.password,
                    email=customer.personal_info.email,
                    pname=join_nonempty_strs([customer.personal_info.first_name, customer.personal_info.last_name]),
                    cname=customer.company,
                    # In PMS there are no resellers, so all customers belong to administrator,
                    # so we don't specify owner ID
                    owner_id=None,
                    address=customer.personal_info.address,
                    city=customer.personal_info.city,
                    country=customer.personal_info.country_code,
                    pcode=customer.personal_info.postal_code,
                    phone=customer.personal_info.primary_phone,
                    fax=customer.personal_info.fax,
                    state=customer.personal_info.state,
                    locale=customer.personal_info.locale,
                    description=customer.description
                )
            ))
        )
        return result.data.customer_id, []
