from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse

from django.forms import model_to_dict
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

from .utils import send_change_of_address_email

from . import forms
from . import profile


def profile_create(request, template="accounts/full_profile_form.html"):
    """ Allows user to create an account """
    userform = forms.ProfileCreateForm(
        request.POST or None, initial={"country": "US"}, prefix="form2"
    )
    second_address_form = forms.ProfileSecondaryAddressForm(
        request.POST or None, initial={"country": "US"}, prefix="form5"
    )

    if request.method == "POST":
        if userform.is_valid() and second_address_form.is_valid():
            user = userform.save(request=request)
            second_address_form.save(user=user)
            return HttpResponseRedirect(reverse("profile_create_complete"))

    return render_to_response(
        template,
        {"userform": userform, "second_address": second_address_form},
        context_instance=RequestContext(request),
    )


def profile_create_complete(request, template="accounts/profile_create_complete.html"):
    return render_to_response(template, context_instance=RequestContext(request))


@login_required
def profile_edit(request, template="accounts/full_profile_form.html"):
    """ Allows a user to edit their profile """
    user = request.user
    user_profile = profile.get_profile(user)
    secondary_address = profile.get_profile_secondary_address(user)

    primary_initial = model_to_dict(user)
    primary_initial.update(model_to_dict(user_profile))
    secondary_initial = model_to_dict(secondary_address)

    userform = forms.ProfileUpdateForm(
        user, request.POST or None, initial=primary_initial, prefix="form2"
    )
    second_address_form = forms.ProfileSecondaryAddressForm(
        request.POST or None, initial=secondary_initial, prefix="form5"
    )

    if request.method == "POST":
        if userform.is_valid() and second_address_form.is_valid():
            user = userform.save()
            second_address_form.save(user=user)

            send_change_of_address_email(
                None, None, None, None, None, primary_initial, userform.cleaned_data
            )

    return render_to_response(
        template,
        {"userform": userform, "second_address": second_address_form},
        context_instance=RequestContext(request),
    )


@login_required
def view_orders_subs(request, template="accounts/orders_subs_overview.html"):

    return render_to_response(template, {}, context_instance=RequestContext(request))
