from django import forms
from django.conf import settings

from oscar.apps.address.forms import UserAddressForm as BaseUserAddressForm
from oscar.core.loading import get_model

Country = get_model("address", "Country")


class UserAddressForm(BaseUserAddressForm):
    field_order = settings.OSCAR_ADDRESS_FORM_FIELD_ORDER

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.adjust_country_field()

    def adjust_country_field(self):
        countries = Country._default_manager.filter(  # pylint: disable=W0212
            is_shipping_country=True
        )

        # No need to show country dropdown if there is only one option
        if len(countries) == 1:
            self.fields["country"].widget = forms.HiddenInput()
            self.fields["country"].initial = self.instance.country = countries.get()
        else:
            self.fields["country"].queryset = countries
            self.fields["country"].empty_label = None

    class Meta(BaseUserAddressForm.Meta):
        fields = settings.OSCAR_ADDRESS_FORM_FIELDS
