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

newsletter_client = MailChimp(settings.MAILCHIMP_API_KEY, settings.MAILCHIMP_USERNAME)
newsletter_field_names = {
    'FNAME': _('Vorname'),
    'LNAME': _('Nachname'),
}


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 = newsletter_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': newsletter_field_names[field['tag']]}
                    )
                )

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

            try:
                newsletter_client.lists.members.create_or_update(
                    settings.MAILCHIMP_LIST_ID,
                    hashlib.md5(cleaned_data['email'].lower().encode('utf-8')).hexdigest(),
                    {
                        'email_address': cleaned_data['email'],
                        'language': get_language(),
                        'status_if_new': 'subscribed',
                        '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.')
                    )
