""" Checkout forms """
from django import forms
from store_order.models import Order
import re


def strip_non_numbers(data):
    """ gets rid of all non-number characters """
    non_numbers = re.compile(r"\D")
    return non_numbers.sub("", data)


# Currently not used, can remove if we don't need in future
class CheckoutForm(forms.ModelForm):
    """ checkout form class to collect user billing and
    shipping information for placing an order """

    def __init__(self, *args, **kwargs):
        super(CheckoutForm, self).__init__(*args, **kwargs)
        # override default attributes
        for field in self.fields:
            self.fields[field].widget.attrs["size"] = "30"

        self.fields["shipping_state"].widget.attrs["size"] = "3"

        self.fields["billing_state"].widget.attrs["size"] = "3"
        self.fields["billing_zip"].widget.attrs["size"] = "6"

    class Meta:
        model = Order
        exclude = ("status", "ip_address", "user", "transaction_id")

    def clean_phone(self):
        """ Validate the phone field """
        phone = self.cleaned_data["phone"]
        stripped_phone = strip_non_numbers(phone)
        if len(stripped_phone) < 10:
            error_str = (
                "Enter a valid phone number with area code." "(e.g. 555-555-5555)"
            )
            raise forms.ValidationError(error_str)
        return self.cleaned_data["phone"]
