from copy import copy

from django.conf import settings
from django.utils.functional import cached_property


class AddressMixin(object):
    @cached_property
    def ordered_base_fields(self):
        base_fields = copy(self.base_fields)
        fields = []
        for key in settings.OSCAR_ADDRESS_BASE_FIELD_ORDER:
            try:
                base_fields.remove(key)
                fields.append(key)
            except ValueError:  # ignore unknown fields
                pass

        return fields + base_fields

    @cached_property
    def ordered_active_address_fields(self):
        """
        active_address_fields renders the address under each other.
        This looks weird on the thankyou page etc, so that's why this is created.
        """

        self.line1 = self.join_fields(("line1", "house_number"), separator=" ")
        self.line4 = self.join_fields(("postcode", "line4"), separator=" ")
        old_fields = ["house_number", "postcode"]

        self.base_fields = [
            field for field in self.base_fields if field not in old_fields
        ]

        return self.get_address_field_values(self.ordered_base_fields)
