from collections import OrderedDict

from phonenumber_field.phonenumber import PhoneNumber
from rest_framework import serializers

from oscar.forms.mixins import PhoneNumberMixin


class PhoneNumberFormContext(PhoneNumberMixin):
    """
    This class created a context the PhoneNumberMixin can function in, so it
    can be used with a serializer.

    It sets up the variables ``cleaned_data``, ``region``, ``country`` and
    provides and add_error function.
    """

    def add_error(self, field_name, error):
        errors = OrderedDict()
        errors[field_name] = error
        raise serializers.ValidationError(errors)

    def __init__(self, data):
        # don't call super, it does some shit we don't want
        # pylint: disable=super-init-not-called

        if "phone_number" in data:
            phone_number = data["phone_number"]

            # Newer versions of django-phonenumber-field has implemented to_python on the model field
            # which returns the PhoneNumber object, but we use this class in .serialziers.py to call the
            # clean_phone_number_field method which expects to work with a string.
            if isinstance(phone_number, PhoneNumber):
                data["phone_number"] = phone_number.raw_input

        self.cleaned_data = data
        self.country = data.get("country", None)
        # 3. PhoneNumberMixin uses region_code
        if self.country is not None:
            self.region_code = self.country.iso_3166_1_a2
