# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _, get_language
from django import forms
from django.conf import settings
from mailchimp3 import MailChimp

client = MailChimp(settings.MAILCHIMP_USERNAME, settings.MAILCHIMP_API_KEY)
field_names = [_('First Name'), _('Last Name')]


class NewsletterSubscriptionForm(forms.Form):
    email = forms.EmailField(max_length=254, label=_('E-Mail'),
                             widget=forms.TextInput(attrs={'placeholder': _('E-Mail')}))

    def __init__(self, *args, **kwargs):
        super(NewsletterSubscriptionForm, self).__init__(*args, **kwargs)
        merge_fields = client.lists.merge_fields.all(list_id=settings.MAILCHIMP_LIST_ID, get_all=True)
        for field in merge_fields['merge_fields']:
            if field['type'] == 'text':
                self.fields[field['tag']] = forms.CharField(
                    label=field['name'], required=field['required'],
                    widget=forms.TextInput(
                        attrs={'placeholder': _(field['name'])}
                    )
                )

    def clean(self):
        cleaned_data = super(NewsletterSubscriptionForm, self).clean()
        if not self._errors:
            merge_data = cleaned_data.copy()
            merge_data.pop('email')

            try:
                client.lists.members.create(settings.MAILCHIMP_LIST_ID, {
                    'email_address': cleaned_data['email'],
                    'language': get_language(),
                    'status': 'subscribed',
                    'merge_fields': merge_data,
                })
            except Exception as err:
                json_err = err.response.json()
                if json_err['title'] == 'Member Exists':
                    raise forms.ValidationError(
                        _('Diese E-Mail-Adresse wurde bereits registriert.')
                    )
                else:
                    raise forms.ValidationError(
                        _('Leider ist ein Fehler aufgetreten, bitte versuchen sie es später nochmals.')
                    )
