from parallels.core.logging import get_logger
from parallels.core.logging import log_context
from parallels.plesk.source.expand import messages
from parallels.core.converter.business_objects.resellers import ResellersConverter
from parallels.core import target_data_model

logger = get_logger(__name__)


class ExpandResellersConverter(ResellersConverter):
    def _convert_source_panel_resellers(
        self, source_panel_data, hosting_plans, resellers_migration_list, report, password_holder
    ):
        logger.info(messages.DEBUG_CONVERT_EXPAND_RESELLERS)
        expand_resellers = source_panel_data
        converted_resellers = []
        for reseller in expand_resellers:
            with log_context(reseller.login):
                if resellers_migration_list is None or reseller.login in resellers_migration_list:
                    reseller_report = report.subtarget(u"Reseller", reseller.login)
                    if resellers_migration_list is not None:
                        reseller_migration_list_plan = resellers_migration_list.get(reseller.login)
                    else:
                        reseller_migration_list_plan = None
                    converted_reseller = self._create_target_model_reseller(
                        None,
                        reseller,
                        hosting_plans.get(reseller.login, []),
                        reseller_report,
                        password_holder,
                        None,
                        reseller_migration_list_plan
                    )
                    converted_resellers.append(converted_reseller)
        return converted_resellers

    def _create_target_model_reseller(
        self, plesk_id, reseller, plans, reseller_report, password_holder,
        reseller_source_panel_plan, reseller_migration_list_plan, admin_descriptions=None
    ):
        password_type, password_value = self._get_reseller_password(reseller, reseller_report, password_holder)
        return target_data_model.Reseller(
            login=reseller.login,
            password=password_value,
            password_type=password_type,
            plan_name=reseller_migration_list_plan,
            personal_info=target_data_model.PersonalInfo(
                first_name=reseller.name,
                email=reseller.email,
                address=None,
                city=None,
                state=None,
                postal_code=None,
                language_code=reseller.locale[0:2],
                locale=reseller.locale,
                country_code=None,
                primary_phone=None,
            ),
            is_enabled=reseller.is_active,
            plans={p.name: p for p in plans},
            source='expand',
        )
