from operator import attrgetter
import random
import re
import json

from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, REDIRECT_FIELD_NAME, login as django_login
from django.contrib.auth import login as auth_login
from django.contrib.sites.models import Site
from django.core.mail import EmailMessage
from django.template.context import RequestContext
from django.shortcuts import render, redirect, render_to_response, get_object_or_404
from django.contrib.auth.forms import SetPasswordForm
from django.db.models import Q
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import cache_page

from pychimp import PyChimp

from accounts.models import *
from accounts.forms import *
from mailinglists.forms import ManageForm
from mailinglists.models import Member
from announce.models import get_latest_announcements, get_announce_calendar
from discuss.models import DiscussionThread
from programs.models import DownloadOfTheMonth
from support.models import NewDonation, AutoGeneratedEmail
from orgsubs.models import Organization,ProspectiveUser
from orgsubs.forms import EditOrgSubForm, ManageMemberForm
from utils.template import RhizomePaginator
from utils.helpers import remove_duplicates_and_preserve_order, browse_helper
from artbase.models import ArtworkStub
from commissions.models import ApprovalVote, RankVote, Proposal
from accounts.templatetags.accounts import hash  
from accounts.decorators import membership_required


@csrf_protect
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, 
        authentication_form=RhizomeUserAuthenticationForm):
    
    """
    Displays the login form and handles the login action. 
    This is a more or less acopy of django's default login, but we wanted to 
    auto-route to user's profile upon logging in...
    
    This also handles newly signed up people who want to make a donation.
    The donation form includes a link to login, and when they come to this
    view, we'll activate their account, let them login, and forward them
    to the donate page.
    """

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    
    notice = None
    user_email = request.GET.get('email')
    registration_code = request.GET.get('registration_code')
    user_account = None

    if registration_code:
        # make sure email and registration validation code match
        try:
            user_account = RhizomeUser.objects.get(email = user_email, registration_code = registration_code)
            if not user_account.is_active:
                # first time
                user_account.send_welcome_email()
                user_account.is_active = 1 
                user_account.save()
                notice = 'welcome'
            else:
                #already registered
                notice = 'registered'
        except RhizomeUser.DoesNotExist:
             notice = 'error'

    if request.method == 'POST':
        form = authentication_form(data=request.POST)
        
        if form.is_valid():
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            
            # Heavier security check -- redirects to http://example.com should 
            # not be allowed, but things like /view/?param=http://example.com 
            # should be allowed. This regex checks if there is a '//' *before* a
            # question mark.
            elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                    redirect_to = settings.LOGIN_REDIRECT_URL
            
            # Okay, security checks complete. Log the user in.
            user = form.get_user()
            auth_login(request, user)
                        
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            
            return HttpResponseRedirect('%s' % redirect_to)
            
    else:
        form = authentication_form(request)
    
    request.session.set_test_cookie()
    
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    # messaging
    if form.errors:
        messages.add_message(request, messages.ERROR, 'Either your username and password didn\'t match, or your account is not currently active. If you recently signed up, make sure to click the activation link in your account confirmation email.')
    else:
        if notice == 'error':
            messages.add_message(request, messages.ERROR, 'Either this account has already registered or your registration verification number is invalid.')
        elif notice == 'registered':
            messages.add_message(request, messages.SUCCESS, 'Your account has been activated. Please login to continue.')
        elif notice == 'welcome':
            messages.add_message(request, messages.SUCCESS, 'Welcome to Rhizome! Your account has been activated. Please login to continue with the donation process.')
        elif request.GET.get('next'):
            messages.add_message(request, messages.INFO, 'Please login to continue.')
    
    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }, context_instance=RequestContext(request))

def ajax_login(request):
    '''
    used in the 2013 campaign page, so sending 
    shipping info etc, but provides a general basis
    for logging in with ajax. 
    '''
    context = RequestContext(request)    
    response = None

    if request.method == "POST":
        authentication_form = RhizomeUserAuthenticationForm(data=request.POST)
        if authentication_form.is_valid():
            user = authentication_form.get_user()
            auth_login(request, user)
                        
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            
            if user.get_profile().get_billing_address():
                billing_address = user.get_profile().get_billing_address().to_dict()
            else:
                billing_address = None

            if user.get_profile().get_shipping_address():
                shipping_address =user.get_profile().get_shipping_address().to_dict()
            else:
                shipping_address = None

            response = {
                        "status": "success",
                        "id": user.id,
                        "username": user.username,
                        "first_name": user.first_name,
                        "last_name": user.last_name,
                        "shipping_address":shipping_address,
                        "billing_address" :billing_address
                        }
        else:
            response = {"status": "fail"}

    return HttpResponse(json.dumps(response), mimetype="application/json")

def login_as_user(request, user_id):  
  
    # security check; don't let unauthorized people login  
    request_hash = request.REQUEST.get("hash", "")  
    if request_hash != hash("user", user_id):  
        raise Exception("invalid hash value")  
      
    user = User.objects.get(id=user_id)  
    
    # ADMIN_HASH_SECRET is set in settings.py, can be any secret string   
    user = authenticate(username=user.username, password=settings.ADMIN_HASH_SECRET)  
    django_login(request, user)    
    return HttpResponseRedirect("/")  

def profiles_list(request):
    context = RequestContext(request)    
    sort = request.GET.get("sort")

    breadcrumb = (('Community', '/community/'), ('Profiles', None),)
                
    if sort:
        users = RhizomeUser.objects \
                .filter( \
                    Q(last_name__istartswith=sort) | \
                    Q(first_name__istartswith=sort) | \
                    Q(username__istartswith=sort) \
                ) \
                .filter(visible=True) \
                .filter(is_active=True) \
                .order_by('user__username', 'user__first_name', 'user__last_name')

        cleaned_users = remove_duplicates_and_preserve_order(users)
        accounts_paginator = RhizomePaginator(cleaned_users, per_page=150, url=request.get_full_path())
        
    else:
        users = RhizomeUser.objects \
            .filter(visible=True) \
            .filter(is_active=True) \
            .order_by('-user_rating__rating', 'user__username', 'user__first_name', 'user__last_name')

        accounts_paginator = RhizomePaginator(users, per_page=150, url=request.get_full_path())
            
    alphabet = [chr(i) for i in xrange(ord('a'), ord('z')+1)]       
    
    return render_to_response(
        "accounts/profiles_list.html", 
        {"accounts_paginator": accounts_paginator,
        "alphabet":alphabet,
        "sort":sort,
        "updated_portfolios": get_recently_updated_portfolios(45),
        "grouped": browse_helper(request, accounts_paginator),
        'breadcrumb': breadcrumb
         },
        context
    )

def community(request):
    return render(request, 'accounts/community.html', {
        'discussion_threads': DiscussionThread.objects.filter(is_public=True)[:10],
        'announcements': get_latest_announcements(4),
        'announce_calendar': get_announce_calendar(),
        'updated_portfolios': get_recently_updated_portfolios(15)
    })
    
def register(request):
    # orgsub signup procedures handled in form 
    form = RegistrationUserCreationForm() 
    
    if request.method == 'POST':
        form = RegistrationUserCreationForm(request.POST)
        
        if form.is_valid():
            user = form.save(commit=True)
            amount = form.cleaned_data.get('amount')

            # skip verify email for donors 
            if user.newdonation_set.all():
                return HttpResponseRedirect(user.verification_url)
            else:
                user.send_verification_email(amount=amount)
                return redirect('register_thanks')
        else:
            messages.add_message(request, messages.ERROR, 'There were errors with your registration form. Please check the fields.')
                                
    return render(request, 'accounts/register.html', {'form': form})

def register_thanks(request):
    if 'register_type' in request.GET:
        if request.GET['register_type'] == 'org_sub_member':
            return render(request, 'accounts/orgsub_register_thanks.html')
    else:
        return render(request, 'accounts/register_thanks.html')
    
def orgsub_invite_welcome(request):
    '''
    users can be invited to join via email through the ManageMemberForm found 
    on the orgsub admin page in profiles. this view handles those coming from 
    the link provided in that email
    '''    
    context = RequestContext(request)
    user_email = request.GET.get("email")
    registration_code = request.GET.get("registration_code")
    breadcrumb = (("Welcome",None),)
    notice = None

    try:
        orgsub_prospective_member = ProspectiveUser.objects.get(email=user_email)
    except:
        orgsub_prospective_member = False
              
    if orgsub_prospective_member and registration_code == orgsub_prospective_member.registration_code:   
        orgsub_prospective_member.accepted = 1            
        
        try:
            check_for_user = User.objects.get(email = user_email)
        except User.DoesNotExist:
            check_for_user = None

        if check_for_user:
            orgsub_prospective_member.user = check_for_user
        
        orgsub_prospective_member.save()
                   
        #if user exists, check to see if user is member
        if check_for_user:
            try:
                check_for_membership = RhizomeMembership.objects.get(user = check_for_user)
            except RhizomeMembership.DoesNotExist:
                check_for_membership = False
            
            check_for_user.registration_code = orgsub_prospective_member.registration_code
            check_for_user.is_active = 1
            check_for_user.save()
            
            # if user is member, update existing membership with org_sub that sent invitation
            if check_for_membership:
                check_for_membership.org_sub = orgsub_prospective_member.org_sub
                check_for_membership.update_membership(None, check_for_membership.org_sub.expiration_date)
                check_for_membership.save()
                
            # if user is not member, create membership, add org_sub info, and update
            else:
                new_member_account = RhizomeMembership(user = check_for_user)
                new_member_account.org_sub = orgsub_prospective_member.org_sub
                org_sub_expire_date = orgsub_prospective_member.org_sub.expiration_date
                new_member_account.update_membership(None,org_sub_expire_date)
                new_member_account.save()

        #if user doesn't exist, create both user account and membership
        else:
            username = user_email.split('@')[0]

            try:
                User.objects.get(username=username)
                username = username + str(random.randint(0,1000000))    
            except User.DoesNotExist:
                pass
            password = User.objects.make_random_password(15)
            new_user_account = RhizomeUser(username = username, 
                    email = orgsub_prospective_member.email)
            new_user_account.set_password(password)
            new_user_account.registration_code = orgsub_prospective_member.registration_code
            new_user_account.save() 
            
            welcome_email = EmailMessage()
            welcome_email.subject = "Welcome to Rhizome!"
            welcome_email.body = """
Welcome to Rhizome!

Here's your username and temporary password.

%s / %s

Go here to update your information: http://rhizome.org/profiles/edit/

Thanks,

--The Rhizome Team
            """ % (new_user_account.username, password)
            welcome_email.to = [user_email]
            welcome_email.bcc = [admin[1] for admin in settings.ADMINS]
            welcome_email.send(fail_silently=False)
              
            new_member_account = RhizomeMembership(user = new_user_account)
            new_member_account.org_sub = orgsub_prospective_member.org_sub
            new_member_account.update_membership(None, new_member_account.org_sub.expiration_date)
            new_member_account.save()
            
        user_account = User.objects.get(email = user_email)
        membership = RhizomeMembership.objects.get(user = user_account)
    else:
        user_account = None
        membership = None
        notice = "Either this account has already registered or your \
        registration verification number is invalid."    

    d = {
        "user_account":user_account,
        "membership":membership,
        "breadcrumb":breadcrumb,
        "notice":notice
        }
    
    return render_to_response( "accounts/welcome_orgsub.html", d, context)
        
def welcome(request):
    user_email = request.GET.get('email')
    registration_code = request.GET.get('registration_code')
    notice = None

    try:
        user_account = RhizomeUser.objects.get(email=user_email, registration_code=registration_code)
        if not user_account.is_active:
            user_account.send_welcome_email()
            user_account.is_active = True
            user_account.save()
    except RhizomeUser.DoesNotExist:
        user_account = None
        notice = 'Either this account has already registered or your registration verification number is invalid.'
                
    d = {
        'user_account': user_account,
        'notice': notice
    }
    
    return render(request, 'accounts/welcome.html', d)

def user_profile(request, user):  
    context = RequestContext(request)
    try:
        #in case the url has a user id, send it back to this view with username
        user = get_object_or_404(User, pk=user)
        return HttpResponseRedirect(user_profile, kwargs={"username": user.username})
    except:
        #now really get it
        user = get_object_or_404(User, username=user)
    
    breadcrumb = (("Community","/community"),("%s" % user.get_profile(),None))
    
    if not user.is_active or not user.get_profile().visible: 
        return HttpResponseRedirect("/profiles/anonymous")
        
    address = user.get_profile().address()
    is_member = user.get_profile().is_rhizomemember()
    portfolio = user.get_profile().get_portfolio()
    artbase_portfolio = user.get_profile().get_artbase_portfolio()
    exhibitions = user.get_profile().get_member_exhibitions()
    saved_works = user.get_profile().get_saved_artworks()
    
    blog_posts = user.get_profile().get_blog_posts_for_profile()  
    if blog_posts:
        blog_posts_pages = RhizomePaginator(blog_posts, per_page=5, custom_page_param = "posts", anchor_name="blog_posts", url=request.get_full_path() )
        blog_posts_pages.set_current_page(request.GET.get("posts"))
    else:
        blog_posts_pages = None
    
    #activity stream
    activities = user.get_profile().get_all_activity_stream()
    activities_count = user.get_profile().get_activity_stream_counts(activities)
    auto_checks=[]         
    
    if request.GET:
        #check to see if there are multiple filter values or one single filter value
        if len(request.GET) > 1 or request.GET.get("page") == None and not request.GET.get("posts"):    
            filtered_activities = []
            filtered_activities_append = filtered_activities.append

            for get in request.GET:
                if get != "page" and get !="posts":
                    #grab the requested objects and put them in a list
                    auto_checks.append(get)   
                    if get == "discuss":
                        get = 'Threaded comment'
                    for item in activities:
                        if item.content_type.name == get:
                            filtered_activities_append(item)

            activities = sorted(filtered_activities,key=attrgetter('created'),reverse=True)         
    if activities:
        activities_paginator = RhizomePaginator(activities, per_page=5, anchor_name="activity_stream",url=request.get_full_path())
        activities_paginator.set_current_page(request.GET.get("page"))
    else:
        activities_paginator = None
     
    return render_to_response(
        "accounts/user_profile.html", 
        {"include_object_header": True,
        "user":user,
        "is_member":is_member,
        "portfolio":portfolio,
        "artbase_portfolio":artbase_portfolio,
        "activities_count":activities_count,
        "auto_checks":auto_checks,
        "activities_paginator":activities_paginator,
        "exhibitions":exhibitions,
        "breadcrumb":breadcrumb,
        "saved_works":saved_works,
        "blog_posts_pages":blog_posts_pages
        },
        context
    )

def anonymous_profile(request):
    context = RequestContext(request)
    breadcrumb = (("Community","/community"),("Anonymous",None))
    return render_to_response("accounts/no_profile.html", {"breadcrumb":breadcrumb}, context)

def username_forward(request,username):  
    """
    handles viewing users from admin backend
    """    
    return HttpResponseRedirect("/profiles/%s" % username)

def id_forward(request):  
    """
    handles forwarding of old rhizome profile urls (/profile.php?12345) which passed the user id as the get key only, which is annoying...
    nginx forwards to this view whenever someone requests http://rhizome.org/profile.php?12345
    """    
    if request.GET:
        if len(request.GET) == 1:
            if request.GET.get('user_id'):
                try:
                    user_id = request.GET.get('user_id')
                    user = User.objects.get(id=user_id)
                    return HttpResponseRedirect("/profiles/%s" % user.username)
                except:
                     return HttpResponseRedirect("/profiles/")
            else:
                for key,value in request.GET.items():
                    user_id = key
                    try:
                        user = User.objects.get(id=user_id)
                        return HttpResponseRedirect("/profiles/%s" % user.username)
                    except:
                     return HttpResponseRedirect("/profiles/")
        else:
            return HttpResponseRedirect("/profiles/")
    else:
        return HttpResponseRedirect("/profiles/")    

def miniprofile(request,user):
    context = RequestContext(request)
    
    try:
        user = User.objects.get(pk=user)
    except:
        user = User.objects.get(username=user)
    
    user_description = user.get_profile().description
    miniprofile_content = ''
    
    if user_description:
        miniprofile_content = user_description
    else:
        activity = user.get_profile().get_activity_stream(1)
        miniprofile_content = activity
        for a in activity:
            miniprofile_content = a.content_object
                
    miniprofile_choices = user.get_profile().get_miniprofile_choices()
    
    if miniprofile_choices:
        if len(miniprofile_choices) > 1:  
            choice = random.randint(1,len(miniprofile_choices))    
            if choice == 1:
                miniprofile_content = user.get_profile().get_twitter()
            elif choice == 2:
                activity = rhizomeuser.get_activity_stream(1)
                for a in activity:
                    miniprofile_content = a
            elif choice == 3:
                miniprofile_content = user.get_profile().description        
        else:
            for choice in miniprofile_choices:
                if choice.id == 1:
                    miniprofile_content = user.get_profile().get_twitter()
                elif choice.id == 2:
                     activity = user.get_profile().get_activity_stream(1)
                     miniprofile_content = activity
                elif choice.id == 3:
                    miniprofile_content = user.get_profile().description        
    
    return render_to_response(
        "accounts/miniprofile.html", 
        {"user": user,
        "miniprofile_content": miniprofile_content
         },
        context
        )

@login_required
def edit_profile_forward(request, user):
     return HttpResponseRedirect("/profiles/edit/")   

@login_required
def edit_profile(request): 
    context = RequestContext(request)
    rhizomeuser = request.user.get_profile()
    
    initial_list_data = [l.listid for l in Member.objects.filter(user=rhizomeuser, deleted = 0)]
    
    personal_info_form = EditPersonalInfoForm(instance=rhizomeuser)
    account_info_form = EditAccountInfoForm(instance=rhizomeuser)
    bio_form = EditBioForm(instance=rhizomeuser)
    add_info_form = EditAdditionalInfoForm(instance=rhizomeuser)
   
    try:
        address = rhizomeuser.address('billing')
        address_form = UserBillingAddressForm(instance=address)
    except:
        address_form = UserBillingAddressForm()
    
    set_password_form = SetPasswordForm(rhizomeuser)
    manage_email_form = ManageForm(request.POST or None, initial={'mailinglists':initial_list_data})
    ip_address = request.META.get('REMOTE_ADDR', 'unknown')
    updated = ''
    
    if request.method == 'POST': 
        response = ''           
        if request.POST['form'] == "personal_info":
            
            personal_info_form = EditPersonalInfoForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            
            if personal_info_form.is_valid():
                rhizomeuser = personal_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                
        if request.POST['form'] == "address_form":
            try:
                address_form = UserBillingAddressForm(request.POST or None, instance=address)        
            except:
                address_form = UserBillingAddressForm(request.POST or None)
            if address_form.is_valid():
                address_form.save(rhizomeuser)
                updated = "pass"
            else:
                updated = "fail" 
                          
        if request.POST['form'] == "bio":
            bio_form = EditBioForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))        
            if bio_form.is_valid():
                rhizomeuser = bio_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                
        if request.POST['form'] == "account_info":
            account_info_form = EditAccountInfoForm(request.POST or None, request.FILES or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            if account_info_form.is_valid():
                rhizomeuser = account_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                        
        if request.POST['form'] == "set_password":
            set_password_form = SetPasswordForm(rhizomeuser,request.POST)
            if set_password_form.is_valid():
                rhizomeuser = set_password_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                       
        if request.POST['form'] == "add_info":
            add_info_form = EditAdditionalInfoForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            if add_info_form.is_valid():
                rhizomeuser = add_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
        
        if request.POST['form'] == "manage_email_form":   
            manage_email_form = ManageForm(request.POST)     
            if manage_email_form.is_valid():
                mailinglists = manage_email_form.cleaned_data['mailinglists']
                notice = manage_email_form.save(request, mailinglists)
                updated = "pass"
            else:
                updated = "fail"
        if updated == 'pass':
            moderator.process(rhizomeuser, request)
            return HttpResponseRedirect('/profiles/edit?updated=True')
    
    breadcrumb = (("Profiles", rhizomeuser.get_absolute_url()), ("Edit",None)) 
 
    if rhizomeuser.id == request.user.id:
        return render_to_response(
            "accounts/edit.html",
            {
            "rhizomeuser":rhizomeuser,
            "personal_info_form":personal_info_form,
            "account_info_form":account_info_form,
            "bio_form":bio_form,
            "add_info_form":add_info_form,
            "set_password_form":set_password_form,
            "manage_email_form":manage_email_form,
            "address_form":address_form,
            "updated": updated,
            "breadcrumb":breadcrumb,
            "today": datetime.datetime.now(),
            }, 
            context
            )
    else:
        return HttpResponseRedirect(reverse(profiles_list))

@login_required
def manage_membership(request):
    context = RequestContext(request)
    
    try:
        membership = RhizomeMembership.objects.get(user = request.user)
    except:
        membership = None

    current_download = DownloadOfTheMonth.objects.latest('premier_date')

    breadcrumb = (("Profiles",("/profiles/")), ("Membership Benefits",None)) 
    
    d = {
        "membership": membership,
        "breadcrumb":breadcrumb,
        "download": current_download
        }  
    
    return render_to_response( "accounts/manage_membership.html", d, context)

@login_required
def manage_orgsub(request,user = None):
    context = RequestContext(request)
    updated = None
   
    try:
        membership = RhizomeMembership.objects.get(user = request.user)
    except:
        membership = None
    
    organization = Organization.objects.get(id = membership.org_sub.id)
    
    edit_orgsub_form = EditOrgSubForm(instance = organization) 
    manage_members_form =  ManageMemberForm(initial={'admin':request.user.id,'admin_email':request.user.email,'org':organization.id})
    
    prospective_users = ProspectiveUser.objects.filter(org_sub = organization).exclude(removed=True)
    invitation_notice = ''
    
    breadcrumb = (("Profiles", request.user.get_profile().get_absolute_url()), ("Organizational Subscription",None))
   
    if request.GET.get('remove'):
        prospective_user_id = request.GET.get('remove')
        prospective_user = ProspectiveUser.objects.get(pk=prospective_user_id)

        if prospective_user.user_id: 
            membership_to_remove = RhizomeMembership.objects.get(user=prospective_user.user_id)
            membership_to_remove.org_sub = None
            membership_to_remove.org_sub_admin = None
            membership_to_remove.save()

        prospective_user.removed = True
        prospective_user.save()
    
    if request.POST:
        if request.POST['form'] == "edit_orgsub":  
            edit_orgsub_form = EditOrgSubForm(request.POST or None, instance = organization)
            if edit_orgsub_form.is_valid():
                organization = edit_orgsub_form.save()
                organization.save()
                updated = "pass"
            else:
                updated = "fail" 
                
        if request.POST['form'] == "add_member":  
            add_member_form = ManageMemberForm(request.POST or None)
            if add_member_form.is_valid():
                invitation_notice = add_member_form.save()
            else:
                invitation_notice = "There was a problem with your submission, please check the form." 

    d = {
        "membership": membership, 
        "organization":organization, 
        "edit_orgsub_form":edit_orgsub_form,
        "manage_members_form":manage_members_form, 
        "prospective_users":prospective_users,
        "updated": updated,
        "invitation_notice": invitation_notice,
        "breadcrumb":breadcrumb,
        "today": datetime.datetime.now()
        }
    
    return render_to_response("accounts/manage_orgsub.html", d, context)

def password(request):    
    #simple page for user password management
    context = RequestContext(request)
    breadcrumb = (("Accounts", "/community"),("Manage Account",None))
    d = {"breadcrumb":breadcrumb,}
    return render_to_response("accounts/password_main.html", d,context)
    
def add_artwork_to_favorites(request, user_id, artwork_id):
    context = RequestContext(request)
    user = request.user
    request_user_id = "%s" % request.user.id
    url_user_id = "%s" % user_id
    
    if request.POST and url_user_id == request_user_id:#double check post comes from user
        rhizome_user = user.get_profile()
        
        #check to make sure artwork exists      
        try:
            artwork = ArtworkStub.objects.get(id = artwork_id)
        except:
            artwork = None
            
        if artwork:
            if artwork in rhizome_user.get_saved_artworks():#check to see if we're adding or removing by seeing if artwork already saved
                rhizome_user.saved_artworks.remove(artwork)
                rhizome_user.save()
                return HttpResponse("removed")
            else:
                rhizome_user.saved_artworks.add(artwork)
                rhizome_user.save()
                return HttpResponse("saved")
        else:
            return HttpResponse("no artwork with that id")
    else:
        return HttpResponse("----")
        
def portfolios(request):
    context = RequestContext(request)
    
    breadcrumb = (("Community", "/community"),("Portfolios",None))

    portfolios = get_recently_updated_portfolios()
    
    portfolios_paginator = RhizomePaginator(portfolios, per_page=50, url=request.get_full_path())
            
   
    d= {
        "breadcrumb":breadcrumb,
        "portfolios_paginator": portfolios_paginator,
        "grouped": browse_helper(request, portfolios_paginator),       
     }
    
    return render_to_response("accounts/portfolios.html", d, context)
    
def membership_required(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/")
    context = RequestContext(request)
    breadcrumb = (("Membership Required", ""),)

    d= {
        "breadcrumb":breadcrumb,
        #"include_section_header": True,
        #"wide_section_description": MEMBERSHIP_HEADER,       
     }
    
    return render_to_response("accounts/membership_required.html", d, context)
    
@login_required
def commissions_voting(request): 
    context = RequestContext(request)
    breadcrumb = (('Profiles', request.user.get_profile().get_absolute_url()), ('Commissions Voting', None))

    proposals = Proposal.objects.filter(author=request.user, cycle__is_active=True)
    app_votes = ApprovalVote.objects.filter(user=request.user).filter(proposal__cycle__is_active=True)
    rank_votes = RankVote.objects.filter(user=request.user).filter(proposal__cycle__is_active=True).order_by('rank')
    
    d = {
        'breadcrumb': breadcrumb,
        'app_votes': app_votes,
        'rank_votes': rank_votes,
        'proposals': proposals,
    }
    return render_to_response('accounts/member_voting.html', d, context)


@login_required
def manage_mailchimp_subscriptions(request):
    '''
    - creates a simple form allowing people to un/subscribe 
      to/from mailchimp lists 
    - this is an ssi in the template in case mailchimp delays or problems, 
      don't want their stuff slowing or crashing our stuff
    '''
    context = RequestContext(request)
    manange_mailchimp_form = ManageMailchimpSubscriptionForm(request)
    notification = None
    errors = None

    redirect_path = request.GET.get('parent')

    if request.POST:
        manange_mailchimp_form = ManageMailchimpSubscriptionForm(request, request.POST)
        if manange_mailchimp_form.is_valid():
            mailchimp_api = PyChimp('3cb8530ce9770dc992d48f579b6bb09a-us1')         
            announce_new_status =  manange_mailchimp_form.cleaned_data["announce_subscribe_checkbox"]
            announce_old_status =  manange_mailchimp_form.cleaned_data["announce_subscribed_status"]
            announce_form_mchimp_list = manange_mailchimp_form.cleaned_data["announce_mailchimp_list"]

            news_new_status =  manange_mailchimp_form.cleaned_data["news_subscribe_checkbox"]
            news_old_status =  manange_mailchimp_form.cleaned_data["news_subscribed_status"]
            news_form_mchimp_list = manange_mailchimp_form.cleaned_data["news_mailchimp_list"]

            if announce_old_status != announce_new_status or news_new_status != news_old_status:
                mailchimp_api = PyChimp('3cb8530ce9770dc992d48f579b6bb09a-us1') 
                mchimp_lists = mailchimp_api.lists()  
                
                for mchimp_list in mchimp_lists:
                    if mchimp_list["name"] == announce_form_mchimp_list:
                        #user_info = mailchimp_api.listMemberInfo(mchimp_list["id"], request.user.email)

                        if request.user.first_name:
                            merge_vars = {"FNAME": request.user.first_name, "LNAME": request.user.last_name}
                        else:
                            if announce_form_mchimp_list == "Rhizome Users Announcements":
                                merge_vars = {"FNAME": "Rhizome", "LNAME": "Member"}
                            
                            if announce_form_mchimp_list == "Rhizome Members Announcements":
                                merge_vars = {"FNAME": "Rhizome", "LNAME": "Friend"}
                        
                        if announce_new_status == True:
                            # subscribe request
                            mailchimp_api.listSubscribe(mchimp_list["id"], request.user.email, merge_vars, email_type='html', 
                                    double_optin=False, update_existing=False, replace_interests=True, send_welcome=True)

                        if announce_new_status == False:
                            # unsubscribe request
                            mailchimp_api.listUnsubscribe(mchimp_list["id"], request.user.email, delete_member=False, 
                                    send_goodbye=True, send_notify=True)

                    if mchimp_list["name"] == news_form_mchimp_list:
                        #user_info = mailchimp_api.listMemberInfo(mchimp_list["id"], request.user.email)

                        if request.user.get_full_name():
                            merge_vars = {"FNAME": request.user.first_name, "LNAME": request.user.last_name}

                        elif request.user.first_name:
                            merge_vars = {"FNAME": request.user.first_name, "LNAME": None}

                        else:
                            merge_vars = {"FNAME": request.user.username, "LNAME": None}

                        if news_new_status == True:
                            # subscribe request
                            mailchimp_api.listSubscribe(mchimp_list["id"], request.user.email, merge_vars, email_type='html', 
                                    double_optin=False, update_existing=False, replace_interests=True, send_welcome=True)

                        if news_new_status == False:
                            # unsubscribe request
                            mailchimp_api.listUnsubscribe(mchimp_list["id"], request.user.email, delete_member=False, 
                                    send_goodbye=True, send_notify=True)
                        
        else:
            errors = manange_mailchimp_form.errors
        
        return HttpResponseRedirect("/profiles/edit?updated=True&errors=%s" % errors)

    d= {"form":manange_mailchimp_form}        
    return render_to_response("accounts/forms/manage_mailchimp_subscriptions.html", d, context)


def welcome_email(request):
    context = RequestContext(request)
    source_code = request.GET.get("sc")
    d= {
        "email_body": AutoGeneratedEmail.objects.get(email_title = 'user_welcome_email').email_body   
    }
    return render_to_response("accounts/emails/welcome_email.html", d, context)
    
def conversion_email(request):
    context = RequestContext(request)
    source_code = request.GET.get("sc")

    d= {
        "source_code":source_code,
        "email_body": AutoGeneratedEmail.objects.get(email_title = '30_day_conversion').email_body   
        }       

    if not source_code:
        return render_to_response("accounts/emails/conversion_email_30day.html", d, context)
    elif source_code == "30dc":
        return render_to_response("accounts/emails/conversion_email_30day.html", d, context)
    elif source_code == "60dc":
        d["email_body"] = AutoGeneratedEmail.objects.get(email_title = '60_day_conversion').email_body        
        return render_to_response("accounts/emails/conversion_email_60day.html", d, context)
    else:
        return render_to_response("accounts/emails/conversion_email_30day.html", d, context)
    
def renewal_email(request):
    context = RequestContext(request)
    source_code = request.GET.get("sc")
    user_email = request.GET.get("user")
    
    try:
        user = RhizomeUser.objects.get(email = user_email)    
    except:        
        user = request.user
    
    d= {"user":user,
        "email_body": AutoGeneratedEmail.objects.get(email_title = '30_day_renewal').email_body   
    }    
        
    if not source_code:
        return render_to_response("accounts/emails/renewal_email_30day.html", d, context)
    elif source_code == "30dr":
        return render_to_response("accounts/emails/renewal_email_30day.html", d, context)
    elif source_code == "15dr":
        d["email_body"] = AutoGeneratedEmail.objects.get(email_title = '15_day_renewal').email_body        
        return render_to_response("accounts/emails/renewal_email_15day.html", d, context)
    elif source_code == "expired":
        d["email_body"] = AutoGeneratedEmail.objects.get(email_title = 'day_of_renewal').email_body        
        return render_to_response("accounts/emails/renewal_email_expired.html", d, context)
    elif source_code == "14dcb":
        d["email_body"] = AutoGeneratedEmail.objects.get(email_title = 'comeback_email').email_body        
        return render_to_response("accounts/emails/renewal_email_comeback.html", d, context)
    else:
        d["email_body"] = AutoGeneratedEmail.objects.get(email_title = 'day_of_renewal').email_body        
        return render_to_response("accounts/emails/renewal_email_expired.html", d, context)