# -*- coding: utf-8 -*-

from django.shortcuts import render,render_to_response,redirect
from django.template import RequestContext
from django.template.response import TemplateResponse
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import logout,login,authenticate
from django.contrib.auth.models import User
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required,user_passes_test
from models import Boat,BoatCategory,Member,Outing,Races,MemberWork
from forms import OutingForm,OutingCloseForm,OutingReserveForm,MemberEditForm
from forms import UserEditForm,UserCreateForm,PassWordConfirmForm
from forms import BoatEditForm,BoatCategoryEditForm,RacesEditForm
from forms import MemberWorkCreateForm
import datetime
from django.utils import timezone,translation
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse,reverse_lazy
from dateutil import parser
from pytz import timezone as tz,utc
from django.conf import settings

from django.utils.encoding import smart_text
from cvkbrno.tasks import handle_sendemailwork

import json
import pandas as pd

from requests.utils import quote
from django.utils.translation import ugettext as _
from django.core.exceptions import ObjectDoesNotExist

import unidecode

import django_rq
queue = django_rq.get_queue('default')
queuelow = django_rq.get_queue('low')
queuehigh = django_rq.get_queue('low')

# settings
THISCLUB = "cvkbrno"
LOCALTIMEZONE = tz('Europe/Prague')
TEMPLATEPREFIX = THISCLUB+'_'
USER_LANGUAGE = 'cs'
translation.activate(USER_LANGUAGE)
BLOCKHOURS = 1.5
RACEBLOCKHOURS = 2
RESERVATIONEXPIRYMINUTES = 15
OUTINGDURATIONHOURS = 1.5

# Create your views here.

def distancecount(u):
    member = Member.objects.get(user=u)
    cumdistance = 0
    monthdistance = 0
    yeardistance = 0
    weekdistance = 0
    today = timezone.now().date()
    weeknr = today.isocalendar()[1]
    thisyear = today.year
    thismonth = today.month
    # sum km own rows
    theoutings = Outing.objects.filter(rower=member).filter(status="completed")
    for o in theoutings:
	cumdistance += o.distance
	oyear = o.starttime.year
	oweek = o.starttime.date().isocalendar()[1]
	omonth = o.starttime.month
	if thisyear == oyear:
	    yeardistance += o.distance
	    if thismonth == omonth:
		monthdistance += o.distance
		if weeknr == oweek:
		    weekdistance += o.distance

    theoutings = Outing.objects.filter(otherrowers=member).filter(status="completed")
    for o in theoutings:
	cumdistance += o.distance
	oyear = o.starttime.year
	oweek = o.starttime.date().isocalendar()[1]
	omonth = o.starttime.month
	if thisyear == oyear:
	    yeardistance += o.distance
	    if thismonth == omonth:
		monthdistance += o.distance
		if weeknr == oweek:
		    weekdistance += o.distance

    return [cumdistance,yeardistance,monthdistance,weekdistance]

def distancecountb(boat):
    cumdistance = 0
    monthdistance = 0
    yeardistance = 0
    weekdistance = 0
    today = timezone.now().date()
    weeknr = today.isocalendar()[1]
    thisyear = today.year
    thismonth = today.month
    # sum km own rows
    theoutings = Outing.objects.filter(boat=boat).filter(status="completed")
    for o in theoutings:
	cumdistance += o.distance
	oyear = o.starttime.year
	oweek = o.starttime.date().isocalendar()[1]
	omonth = o.starttime.month
	if thisyear == oyear:
	    yeardistance += o.distance
	    if thismonth == omonth:
		monthdistance += o.distance
		if weeknr == oweek:
		    weekdistance += o.distance

    return [cumdistance,yeardistance,monthdistance,weekdistance]

def getclubmembers():
    members = Member.objects.all().filter(contributions=True).filter(club=THISCLUB)
    return members

def getmembers_json(u):
    members = Member.objects.all().filter(contributions=True).filter(club=THISCLUB).exclude(user=u).order_by('user__last_name')
    dd = {}
    for m in members:
	dd[m.user.id] = m.user.first_name+' '+m.user.last_name

    return json.dumps(dd)

def thisclub_member(user):
    member = Member.objects.get(user=user)
    result = user.is_authenticated() and member.club==THISCLUB and member.contributions
    return result

def thisclub_admin(user):
    if user.is_authenticated():
	member = Member.objects.get(user=user)
	result = user.is_authenticated() and member.club==THISCLUB and \
		 (member.status in ["administrator","coach"])
    else:
	result = False

    return result

def conflicting_reservations(boat,starttime,endtime):
    thisboatoutings = Outing.objects.filter(boat=boat).exclude(status="completed")
    
    check = False
    message = ""
    # starttime = LOCALTIMEZONE.localize(starttime)
    
    for outing in thisboatoutings:
	if (outing.status == "active"):
	    if outing.starttime+datetime.timedelta(hours=OUTINGDURATIONHOURS)>starttime:
		check = True
		message = _("Boat is on the water at that time")
	if (outing.status == "race"):
	    # if boat goes on transport in two hours from reservation time
	    if (outing.starttime < starttime+datetime.timedelta(hours=RACEBLOCKHOURS)):
		check = True
		message = _("Boat is planned to go on transport at that time")
	    # if boat is out racing during reservation time
	    if (outing.endtime > starttime):
		check = True
		message = _("Boat is at races at that time")
	    # if boat is already back frmo racing during reservation time
	    if (outing.endtime <= starttime):
		check = False
		message = ""
	if (outing.status == "reservation"):
	    # check if our reservation end time is before
	    # or our reservation start time is
	    # after this reservation
	    
	    if (outing.starttime < endtime and outing.endtime > starttime):
		check = True
		message = _("Conflicting reservations")

	    if (outing.endtime > starttime) and (outing.starttime < starttime):
		check = True
		message = _("Conflicting reservations")
	if (outing.status == "race"):
	    # check if our reservation end time is before
	    # or our reservation start time is
	    # after this reservation
	    
	    if (outing.starttime-datetime.timedelta(RACEBLOCKHOURS) < endtime and outing.endtime > starttime):
		check = True
		message = _("Boat will go to races at that time")

	    if (outing.endtime > starttime) and (outing.starttime-datetime.timedelta(RACEBLOCKHOURS) < starttime):
		check = True
		message = _("Boat is at races at that time")

    return check,message

def cleanoldreservations():
    reservations = Outing.objects.filter(status="reservation")
    now = timezone.now()
    for reservation in reservations:
	dt = reservation.starttime
	if dt < now-datetime.timedelta(minutes=RESERVATIONEXPIRYMINUTES):
	    reservation.delete()
    # code to change boats that go on transport  and remove boats that have returned from transport
    races = Outing.objects.filter(status="race")
    for race in races:
	if now > race.starttime-datetime.timedelta(hours=RACEBLOCKHOURS):
	    race.boat.status="races"
	    race.boat.save()
	if now > race.endtime:
	    race.boat.status="hangar"
	    race.boat.save()

def get_damagedboats():
    damagedboats = Boat.objects.filter(status="damaged")
    return list(set(damagedboats))

def get_availableboats(m,t):
    hangarboats = Boat.objects.filter(status="hangar")
    cleanoldreservations()
    allowedboats = []
    reservations = Outing.objects.filter(status="reservation")
    starttime = timezone.now()

    # add boats from allowed categories
    for category in m.categories.all():
	thiscategoryboats = hangarboats.filter(categories=category)
	for theboat in thiscategoryboats:
	    thisboatreservations = Outing.objects.filter(status="reservation",boat=theboat)
	    addboat = True
	    # the below should go to a subroutine
	    # do not allow to add boats that go on transport or are reserved
	    # in the near future
	    for res in thisboatreservations:
		if (res.starttime < starttime+datetime.timedelta(hours=OUTINGDURATIONHOURS)):
		    addboat = False
		    if res.rower == m:
			addboat = True
		if (res.endtime):
		    if (res.endtime > starttime):
			addboat = False
			if res.rower == m:
			    addboat=True
	    thisboatrace = Outing.objects.filter(status="race",boat=theboat)
	    for race in thisboatrace:
		if (race.starttime < starttime+datetime.timedelta(hours=RACEBLOCKHOURS)) and (race.endtime > starttime):
		    addboat = False
		    race.boat.status="races"
		    race.boat.save()
		if (race.endtime < starttime):
		    addboat = True
		    race.boat.status="hangar"
		    race.boat.save()

	    if addboat:
		allowedboats += [theboat]

	    

    return list(set(allowedboats))

def get_availableboats_reservation(m,t):
    hangarboats = Boat.objects.filter(status__in = ["hangar","water","reservation","races"])
    allowedboats = []
    cleanoldreservations()
    reservations = Outing.objects.filter(status="reservation")
    # code to remove reservations from list of hangar boats
    # & clear reservations that are >15 min beyond start time

    # code to remove boats that go on transport within two hours


    # add boats from available categories
    for category in m.categories.all():
	allowedboats += hangarboats.filter(categories=category)

    return list(set(allowedboats))


def get_active_outings():
    activeoutings = Outing.objects.filter(status="active")

    return activeoutings

def get_future_reservations():
    cleanoldreservations()
    reservations = Outing.objects.filter(status="reservation").order_by("starttime")
    return reservations

def get_future_races():
    cleanoldreservations()
    races = Races.objects.filter(startdatetime__gt=timezone.now()).order_by("startdatetime")
    return races

def login_user_view(request,activeoutings=get_active_outings(),reservations=get_future_reservations()):
    logout(request)
    request.session[translation.LANGUAGE_SESSION_KEY] = USER_LANGUAGE
    username = password = ''
    if request.POST:
	username = request.POST['username']
	password = request.POST['password']

	user = authenticate(username=username, password=password)
	if user is not None:
            if user.is_active:
                login(request, user)
		url = reverse(base_view)
                return HttpResponseRedirect(url)
    return render(request,'cvkbrno_login.html',
		  {'activeoutings':get_active_outings(),
		   'reservations':get_future_reservations()})

def change_language_view(request,languagecode):
    USER_LANGUAGE = languagecode
    translation.activate(USER_LANGUAGE)
    request.session[translation.LANGUAGE_SESSION_KEY] = USER_LANGUAGE
    url = request.META.get('HTTP_REFERER','/')
    return HttpResponseRedirect(url)

@login_required(login_url='/cvkbrno/login/')
def base_view(request):
    cleanoldreservations()
    request.session[translation.LANGUAGE_SESSION_KEY] = USER_LANGUAGE
    # Switcher between different views depending on user's status
    member = Member.objects.get(user=request.user)
    activeoutings = Outing.objects.filter(status="active",rower=member)
    if (len(activeoutings)!=0):
	# we are still out
	url = reverse(closeouting_view)
	return HttpResponseRedirect(url)
    else:
	url = reverse(createouting_view)
	return HttpResponseRedirect(url)



def logout_then_login(request):
    logout(request)
    extra_context = {'activeoutings':get_active_outings()}
    context = RequestContext(request)
    context.update(extra_context)
    activeoutings = get_active_outings()
    url = reverse(base_view)
    return HttpResponseRedirect(url)

			 

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def boats_admin_view(request,message="",successmessage=""):
    cleanoldreservations()
    theboats = Boat.objects.all().order_by("boatcode")
    theoutings = Outing.objects.exclude(status="reservation").exclude(status="race").order_by("-starttime")[0:20]
    return render(request,
	   TEMPLATEPREFIX+'boats_admin.html',
	   {'theboats':theboats,
	    'theoutings':theoutings,
	    'message':message,
	    'successmessage':successmessage,
	    'thisclub_admin':thisclub_admin(request.user),
	    'worked_hours':Member.objects.get(user=request.user).hoursworked,})


@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def categories_admin_view(request,message="",successmessage=""):
    cleanoldreservations()
    thecats = BoatCategory.objects.all().order_by("name")
    return render(request,
	   TEMPLATEPREFIX+'categories_admin.html',
	   {'thecats':thecats,
	    'message':message,
	    'successmessage':successmessage,
	    'thisclub_admin':thisclub_admin(request.user),
	    'worked_hours':Member.objects.get(user=request.user).hoursworked,})

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_admin_view(request,message="",successmessage=""):
    cleanoldreservations()
    themembers = Member.objects.filter(club=THISCLUB).order_by('user')


    return render(request,
		  TEMPLATEPREFIX+'members_admin.html',
		  {'themembers':themembers,
		   'message':message,
		   'successmessage':successmessage,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})
		   

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_work_admin_view(request,message="",successmessage=""):
    cleanoldreservations()
    theworks = MemberWork.objects.filter(status='planned')
    return render(request,
		  TEMPLATEPREFIX+'memberswork_admin.html',
		  {'theworks':theworks,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})


@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_work_add_view(request,message="",successmessage=""):
    cleanoldreservations()
    if request.method == 'POST':
	# Form was submitted
	form = MemberWorkCreateForm(request.POST)

	if form.is_valid():
	    # do something
	    res = addmemberwork(request.POST)	    
	    func = res[0]
	    message = res[1]
	    successmessage = res[2]
	    theid = res[3]
	    kwargs = {}
	    if successmessage != "":
		kwargs['successmessage'] = successmessage.encode('utf8')
	    if message != "":
		kwargs['message'] = message.encode('utf8')

	    theworks = MemberWork.objects.filter(status='planned')
#	    args['theworks'] = theworks

	    url = reverse(func,kwargs = kwargs)
		
	    return HttpResponseRedirect(url)
	else:
	    return render(request,
			  TEMPLATEPREFIX+'memberswork_add_form.html',
			  {'form':form,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user),
			   }
			  )
			  
    else:
	form = MemberWorkCreateForm()
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'memberswork_add_form.html',
			  {'form':form,
			   'message':message,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'memberswork_add_form.html',
			  {'form':form,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def boats_admin_delete_confirm_view(request,id):
    theboat = Boat.objects.get(id=id)
    return render(request,
		  TEMPLATEPREFIX+'boat_delete_confirm.html',
		  {'id':id,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def outing_admin_view(request,id):
    theouting = Outing.objects.get(id=id)
    return render(request,
		  TEMPLATEPREFIX+'outing_admin.html',
		  {'outing':theouting,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def categories_admin_delete_confirm_view(request,id):
    thecategory = BoatCategory.objects.get(id=id)
    return render(request,
		  TEMPLATEPREFIX+'categories_delete_confirm.html',
		  {'id':id,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_admin_delete_confirm_view(request,id):
    themember = Member.objects.get(id=id)
    return render(request,
		  TEMPLATEPREFIX+'members_delete_confirm.html',
		  {'id':id,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def boats_admin_delete_view(request,id):
    try:
	theboat = Boat.objects.get(id=id)
	theboat.delete()
    except:
	pass

    url = reverse(boats_admin_view,kwargs={
	'successmessage': _("boat deleted").encode('utf8'),
	})

    return HttpResponseRedirect(url)


@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_admin_delete_view(request,id):
    try:
	themember = Member.objects.get(id=id)
	themember.user.delete()
	themember.delete()
    except:
	pass

    url = reverse(members_admin_view,kwargs={
	'successmessage': _("member deleted").encode('utf8'),
	})

    return HttpResponseRedirect(url)

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def categories_admin_delete_view(request,id):
    try:
	thecategory = BoatCategory.objects.get(id=id)
	thecategory.delete()
    except:
	pass

    url = reverse(categories_admin_view,kwargs={
	'successmessage': _("category deleted").encode('utf8'),
	})

    return HttpResponseRedirect(url)



@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def boats_admin_add_view(request,message="",successmessage=""):
    if request.method == 'POST':
	# Form was submitted
	form = BoatEditForm(request.POST)

	if form.is_valid():
	    # do something
	    res = addboat(request.POST)
	    func = res[0]
	    message = res[1]
	    successmessage = res[2]
	    theid = res[3]
	    kwargs = {}
	    if successmessage != "":
		kwargs['successmessage'] = successmessage.encode('utf8')
	    if message != "":
		kwargs['message'] = message.encode('utf8')
	    if theid != 0:
		kwargs['id'] = int(theid)
	    url = reverse(func,kwargs = kwargs)
		
	    return HttpResponseRedirect(url)
	else:
	    return render(request,
			  TEMPLATEPREFIX+'boat_add_form.html',
			  {'form':form,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user),
			   }
			  )
			  
    else:
	form = BoatEditForm()
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'boat_add_form.html',
			  {'form':form,
			   'message':message,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'boat_add_form.html',
			  {'form':form,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_admin_add_view(request,message="",successmessage=""):
    if request.method == 'POST':
	# Form was submitted
	form = MemberEditForm(request.POST)

	if form.is_valid():
	    # do something
	    res = addmember(request.POST)
	    func = res[0]
	    message = res[1]
	    successmessage = res[2]
	    theid = res[3]
	    kwargs = {}
	    if successmessage != "":
		kwargs['successmessage'] = successmessage
	    if message != "":
		kwargs['message'] = message
	    if theid != 0:
		kwargs['id'] = int(theid)
	    url = reverse(func,kwargs = kwargs)
		
	    return HttpResponseRedirect(url)
	else:
	    memberform = form
	    userform = UserCreateForm()
	    passwordconfirmform = PassWordConfirmForm()
	    return render(request,
			  TEMPLATEPREFIX+'member_add_form.html',
			  {'form1':memberform,
			   'form2':userform,
			   'form3':passwordconfirmform,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
			  
    else:
	memberform = MemberEditForm()
	userform = UserCreateForm()
	passwordconfirmform = PassWordConfirmForm()
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'member_add_form.html',
			  {'form1':memberform,
			   'form2':userform,
			   'form3':passwordconfirmform,
			   'message':message,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'member_add_form.html',
			  {'form1':memberform,
			   'form2':userform,
			   'form3':passwordconfirmform,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )


@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def categories_admin_add_view(request,message="",successmessage=""):
    if request.method == 'POST':
	# Form was submitted
	form = BoatCategoryEditForm(request.POST)

	if form.is_valid():
	    # do something
	    message = ""
	    successmessage = ""
	    name = request.POST['name']
	    thecategory = BoatCategory(name=name)
	    thecategory.save()
	    kwargs = {}
	    if message != "":
		kwargs['message'] = message
	    if successmessage != '':
		kwargs['successmessage'] = successmessage

	    url = reverse(categories_admin_view,kwargs=kwargs)
		
	    return HttpResponseRedirect(url)
	else:
	    return render(request,
			  TEMPLATEPREFIX+'category_add_form.html',
			  {'form':form,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )

    else:
	form = BoatCategoryEditForm()
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'category_add_form.html',
			  {'form':form,
			   'message':message,
			   'successmessage':successmessage,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'category_add_form.html',
			  {'form':form,
			   'successmessage':successmessage,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
    

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def boats_admin_edit_view(request,id,message="",successmessage=""):
    theboat = Boat.objects.get(id=id)
    if request.method == 'POST':
	# Form was submitted
	form = BoatEditForm(request.POST)

	if form.is_valid():
	    res = editboat(request.POST,theboat)
	    func = res[0]
	    message = res[1]
	    successmessage = res[2]
	    theid = res[3]
	    kwargs = {}
	    if successmessage != "":
		kwargs['successmessage'] = successmessage
	    if message != "":
		kwargs['message'] = message
	    if theid != 0:
		kwargs['id'] = int(theid)
	    url = reverse(func,kwargs = kwargs)
		
	    return HttpResponseRedirect(url)
	else:
	    theoutings = Outing.objects.exclude(status="reservation").filter(boat=theboat).order_by("-starttime")[0:20]
	    return render(request, 
			  TEMPLATEPREFIX+'boat_edit_form.html',
			  {'form':form,
			   'theoutings':theoutings,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	    
    else:
	form = BoatEditForm(instance=theboat)
	theoutings = Outing.objects.exclude(status="reservation").filter(boat=theboat).order_by("-starttime")[0:20]
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'boat_edit_form.html',
			  {'form':form,
			   'message':message,
			   'theoutings':theoutings,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'boat_edit_form.html',
			  {'form':form,
			   'theoutings':theoutings,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_work_edit_view(request,id,message="",successmessage=""):
    thework = MemberWork.objects.get(id=id)
    if request.method == 'POST':
	# Form was submitted
	form = MemberWorkCreateForm(request.POST)

	if form.is_valid():
	    res = editmemberwork(request.POST,thework)
	    func = res[0]
	    message = res[1]
	    successmessage = res[2]
	    theid = res[3]
	    kwargs = {}
	    if successmessage != "":
		kwargs['successmessage'] = successmessage
	    if message != "":
		kwargs['message'] = message
	    if theid != 0:
		kwargs['id'] = int(theid)
	    url = reverse(func,kwargs = kwargs)
		
	    return HttpResponseRedirect(url)
	else:
	    return render(request, 
			  TEMPLATEPREFIX+'memberwork_edit_form.html',
			  {'form':form,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	    
    else:
	form = MemberWorkCreateForm(instance=thework)
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'memberwork_edit_form.html',
			  {'form':form,
			   'message':message,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'memberwork_edit_form.html',
			  {'form':form,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_admin_edit_view(request,id,message="",successmessage=""):
    themember = Member.objects.get(id=id)
    if request.method == 'POST':
	# Form was submitted
	form = MemberEditForm(request.POST)

	if form.is_valid():
	    res = editmember(request.POST,themember)
	    func = res[0]
	    message = res[1]
	    successmessage = res[2]
	    theid = res[3]
	    kwargs = {}
	    if successmessage != "":
		kwargs['successmessage'] = successmessage
	    if message != "":
		kwargs['message'] = message
	    if theid != 0:
		kwargs['id'] = int(theid)
	    url = reverse(func,kwargs = kwargs)
		
	    return HttpResponseRedirect(url)
	else:
	    return render(request, 
			  TEMPLATEPREFIX+'member_edit_form.html',
			  {'form1':memberform,
			   'form2':userform,
			   'id':id,
			   'username': themember.user.username,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )

	    
    else:
	memberform = MemberEditForm(instance=themember)
	userform = UserEditForm(instance=themember.user)
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'member_edit_form.html',
			  {'form1':memberform,
			   'form2':userform,
			   'username': themember.user.username,
			   'message':message,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'member_edit_form.html',
			  {'form1':memberform,
			   'form2':userform,
			   'username': themember.user.username,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )


@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def categories_admin_edit_view(request,id,message="",successmessage=""):
    thecategory = BoatCategory.objects.get(id=id)
    if request.method == 'POST':
	# Form was submitted
	form = BoatCategoryEditForm(request.POST)

	if form.is_valid():
	    # do something
	    message = ""
	    successmessage = ""
	    name = request.POST['name']
	    thecategory.name = name
	    thecategory.save()

	    	    
	    if (message != ""):
		url = reverse(categories_admin_view,
			      kwargs = {
				  'successmessage': _('Changes saved'),
				  'message': message
				  })
	    else:
		url = reverse(categories_admin_view,
			      kwargs = {
				  'successmessage': _('Changes saved'),
				  })
		
	    return HttpResponseRedirect(url)
	else:
	    return render(request, 
			  TEMPLATEPREFIX+'categories_edit_form.html',
			  {'form':form,
			   'successmessage':successmessage,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
    else:
	form = BoatCategoryEditForm(instance=thecategory)
	if (message != ""):
	    return render(request, 
			  TEMPLATEPREFIX+'categories_edit_form.html',
			  {'form':form,
			   'message':message,
			   'successmessage':successmessage,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )
	else:
	    
	    return render(request, 
			  TEMPLATEPREFIX+'categories_edit_form.html',
			  {'form':form,
			   'successmessage':successmessage,
			   'id':id,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,}
			  )

@user_passes_test(thisclub_member,login_url="/cvkbrno/login")
def meterboard_view(request,message="",successmessage="",sortby="year"):
    try:
	sortby = request.GET['sortby']
    except KeyError:
	pass
    now = timezone.now()
    members = getclubmembers()
    boats = Boat.objects.all()
    df = pd.DataFrame()
    dfb = pd.DataFrame()
    theoutings = Outing.objects.exclude(status="reservation").exclude(status="race").order_by("-starttime")[0:20]

    for member in members:
	cumdist,yeardist,monthdist,weekdist = distancecount(member.user)
	df2 = pd.DataFrame(
	    {
		'Cumulative Distance':[cumdist],
		'This Year':[yeardist],
		'This Month':[monthdist],
		'This Week':[weekdist],
		},
	    index = [member]
	    )
	df = df.append(df2)

    for boat in boats:
	cumdist,yeardist,monthdist,weekdist = distancecountb(boat)
	df3 = pd.DataFrame(
	    {
		'Cumulative':[cumdist],
		'This Year':[yeardist],
		'This Month':[monthdist],
		'This Week':[weekdist],
		},
	    index = [boat]
	    )
	dfb = dfb.append(df3)

    sortorder = ['This Year', 'This Month', 'This Week']
    if sortby == 'month':
	sortorder = ['This Month','This Year','This Week']
    if sortby == 'week':
	sortorder = ['This Week','This Year','This Month']
	
    data = df.sort_values(by=sortorder,ascending=False).to_html(classes='listtable paddedtable',columns=['This Year','This Month','This Week'])
    datab = dfb.sort_values(by=sortorder,ascending=False).to_html(classes='listtable paddedtable',columns=['This Year','This Month','This Week'])
    return render(request,
		  TEMPLATEPREFIX+'meterboard.html',
		  {'data':data,
		   'datab':datab,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})
		   
    

@user_passes_test(thisclub_member,login_url="/cvkbrno/login")
def createouting_view(request,message="",successmessage=""):
    cleanoldreservations()
    today = timezone.now().date()
    member = Member.objects.get(user=request.user)
    activeoutings = Outing.objects.filter(rower=member,status="active")
    theboats = get_availableboats(member,timezone.now())
    plannedwork = MemberWork.objects.filter(status='planned')

    # You are still out
    if (len(activeoutings)!=0):
	# we are still out
	errormessg = _("You still have an active outing. Check in first.").encode('utf8')
	url = reverse(closeouting_view,
			      kwargs = {
				  'message':str(errormessg),
				  })

	return HttpResponseRedirect(url)
    # You have submitted the form
    if request.method == 'POST':
	# Form was submitted
	form = OutingForm(request.POST)
	# form is valid
	if form.is_valid():
	    # Get values from form
	    dist = request.POST['distance']
	    boat = Boat.objects.get(id=request.POST['boat'])
	    boat.status = "water"
	    boat.save()
	    additionalcrew = []
	    if boat.nrseats>1:
		for i in range(boat.nrseats-1):
		    snr = i+2
		    try:
			crewid = int(request.POST['crew'+str(snr)])
		    except:
			message = _("You must select additional crew members for this boat")
			return render(request,
				      TEMPLATEPREFIX+'outing_form.html',
				      {'form':form,
				       'theboats':theboats,
				       'reservations':get_future_reservations(),
				       'races':get_future_races(),
				       'damagedboats':get_damagedboats(),
				       'plannedwork':plannedwork,
				       'member':member,
				       'message':message,
				       'jsonmembers':getmembers_json(request.user),
				       'successmessage':successmessage,
				       'thisclub_admin':thisclub_admin(request.user),
				       'worked_hours':Member.objects.get(user=request.user).hoursworked,})
		    additionalcrew.append(Member.objects.get(user__id=crewid))
	    # remove duplicates
	    additionalcrew = list(set(additionalcrew))

		    
	    starttime = timezone.now()
	    myreservations = Outing.objects.filter(status="reservation",
						   rower=member,
						   starttime__year=today.year,
						   starttime__month=today.month,
						   starttime__day=today.day).order_by("starttime")

	    # form is valid and you have some reservation (for today)
	    if len(myreservations) != 0:
		nextreservation=myreservations.first()
		# you are taking the boat that you reserved

		if (nextreservation.boat == boat):
		    nextreservation.starttime = starttime
		    nextreservation.status = "active"
		    nextreservation.distance = dist
		    nextreservation.save()
		    for member in additionalcrew:
			nextreservation.otherrowers.add(member)
			nextreservation.save()
		# you are taking another boat
		else:
		    o = Outing(starttime=starttime,rower=member,
			       boat=boat,distance=dist,
			       status="active")
		    o.save()
		    for member in additionalcrew:
			o.otherrowers.add(member)
			o.save()
	    # form is valid and you have no reservations
	    else:
		o = Outing(starttime=starttime,rower=member,boat=boat,
			   distance=dist,
			   status="active")
		o.save()
		for member in additionalcrew:
		    o.otherrowers.add(member)
		    o.save()
	    if not settings.DEBUG:
		logout(request)
	    url = reverse(base_view)
	    return HttpResponseRedirect(url)
	# You have not submitted a form with errors
	else:
	    return render(request,
			  TEMPLATEPREFIX+'outing_form.html',
			  {'form':form,
			   'theboats':theboats,
			   'reservations':get_future_reservations(),
			   'races':get_future_races(),
			   'member':member,
			   'damagedboats':get_damagedboats(),
			   'plannedwork':plannedwork,
			   'message':message,
			   'jsonmembers':getmembers_json(request.user),
			   'successmessage':successmessage,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,})
    # You have not submitted the form
    else:
	form = OutingForm(
	    initial={'distance':12,
		     }
		)
	today = timezone.now().date()
	myreservations = Outing.objects.filter(status="reservation",
					       rower=member,
					       starttime__year=today.year,
					       starttime__month=today.month,
					       starttime__day=today.day).order_by("starttime")


	form = OutingForm(
	    initial={
		'distance':12,
		})
	return render(request, 
		      TEMPLATEPREFIX+'outing_form.html',
		      {'form':form,
		       'theboats':theboats,
		       'reservations':get_future_reservations(),
		       'member':member,
		       'races':get_future_races(),
		       'damagedboats':get_damagedboats(),
		       'plannedwork':plannedwork,
		       'message':message,
		       'successmessage':successmessage,
		       'jsonmembers':getmembers_json(request.user),
		       'thisclub_admin':thisclub_admin(request.user),
		       'worked_hours':Member.objects.get(user=request.user).hoursworked,})

	
@user_passes_test(thisclub_member,login_url="/cvkbrno/login")
def closeouting_view(request,message="",successmessage=""):
    cleanoldreservations()
    member = Member.objects.get(user=request.user)
    activeoutings = Outing.objects.filter(rower=member,status="active")
    if (len(activeoutings)==0):
	# no active outings
	errormessg = _("You have no active outings. Go rowing first.").encode('utf8')
	url = reverse(createouting_view,
			      kwargs = {
				  'message':str(errormessg),
				  })

	return HttpResponseRedirect(url)
    if request.method == 'POST':
	# Form was submitted
	form = OutingCloseForm(request.POST)
	if form.is_valid():
	    # Get values from form
	    dist = request.POST['distance']
	    comment = request.POST['comment']
	    endtime = timezone.now()
	    damagecheck = request.POST['damagecheck']
	    o = Outing.objects.get(rower=member,status="active")
	    if (damagecheck == "No"):
		o.boat.status = _("damaged")
		o.boat.comment += "\n"+timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S')
		o.boat.comment += " "+comment
	    else:
		o.boat.status = "hangar"
	    o.boat.save()
	    o.endtime = endtime
	    o.comment = comment
	    o.distance = dist
	    o.status = "completed"
	    o.save()
	    if not settings.DEBUG:
		logout(request)
	    url = reverse(base_view)
	    return HttpResponseRedirect(url)
	
    else:
	outing = Outing.objects.get(rower=member,status="active")
	form = OutingCloseForm()
	return render(request, 
		      TEMPLATEPREFIX+'outing_closeform.html',
		      {'form':form,
		       'outing':outing,
		       'thisclub_admin':thisclub_admin(request.user),
		       'message':message,
		       'worked_hours':Member.objects.get(user=request.user).hoursworked,})

def get_races(datum):
    allraces = Races.objects.filter(enddatetime__gt=datum)
    return allraces

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def transport_view(request,message="",successmessage=""):
    cleanoldreservations()
    theraces = get_future_races()
    return render(request,
		  TEMPLATEPREFIX+'races_list.html',
		  {'races':theraces,
		   'thisclub_admin':thisclub_admin(request.user),
		   'message':message,
		   'successmessage':successmessage,
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,
		   })


@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def transport_add_view(request,message="",successmessage=""):
    cleanoldreservations()
    member = Member.objects.get(user=request.user)
    theboats = Boat.objects.all().order_by("boatcode")
    if request.method=='POST':
	#Form was submitted
	form = RacesEditForm(request.POST)
	if form.is_valid():
	    # Get values from form
	    name = form.cleaned_data['name']
	    startdate = form.cleaned_data['startdate']
	    starttime = form.cleaned_data['starttime']
	    enddate = form.cleaned_data['enddate']
	    endtime = form.cleaned_data['endtime']
	    transportboats = form.cleaned_data['transportboats']

	    startdatetime = (str(startdate) + ' ' + str(starttime))
	    startdatetime = datetime.datetime.strptime(startdatetime,
						       "%Y-%m-%d %H:%M:%S")
	    startdatetime = timezone.make_aware(startdatetime,
						timezone=LOCALTIMEZONE)
	    enddatetime = (str(enddate) + ' ' + str(endtime))
	    enddatetime = datetime.datetime.strptime(enddatetime,
						       "%Y-%m-%d %H:%M:%S")
	    enddatetime = timezone.make_aware(enddatetime,
					      timezone=LOCALTIMEZONE)

	    r = Races(name=name,
		      startdatetime=startdatetime,
		      enddatetime=enddatetime)

	    r.save()
	    for b in transportboats:
		r.transportboats.add(b)
		o = Outing(starttime=startdatetime,
			   endtime=enddatetime,
			   distance=0,
			   comment=name,
			   boat=b,
			   rower=member,
			   status="race")
		o.save()
		o.race.add(r)
		o.save()

	    r.save()
	    successmessage = _("Race has been saved").encode('utf8')
	    return render(request,
			  TEMPLATEPREFIX+'races_list.html',
			  {
			      'thisclub_admin':thisclub_admin(request.user),
			      'message':message,
			      'races':get_future_races(),
			      'successmessage':successmessage,
			      'worked_hours':Member.objects.get(user=request.user).hoursworked,   
			      })
	else:
	    return render(request, 
			  TEMPLATEPREFIX+'races_form.html',
			  {'form':form,
			   'theboats':theboats,
			   'thisclub_admin':thisclub_admin(request.user),
			   'message':message,
			   'successmessage':successmessage,
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,   })

    else:
	form = RacesEditForm()

	return render(request, 
		      TEMPLATEPREFIX+'races_form.html',
		      {'form':form,
		       'theboats':theboats,
		       'thisclub_admin':thisclub_admin(request.user),
		       'message':message,
		       'successmessage':successmessage,
		       'worked_hours':Member.objects.get(user=request.user).hoursworked,
		       })
    

@user_passes_test(thisclub_admin,login_url="cvkbrno/login")
def races_admin_delete_view(request,id):
    # put in a try except block
    try:
	therace = Races.objects.get(id=id)
	theoutings = Outing.objects.filter(race=therace)


	for outing in theoutings:
	    outing.delete()

	therace.delete()
    except ObjectDoesNotExist:
	pass
    
    successmessage = _("Race deleted")

    url = reverse(transport_view,
		  kwargs={
		      'successmessage':successmessage,
		      })

    return HttpResponseRedirect(url)

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_work_complete_view(request,id=0):
    thework = MemberWork.objects.get(id=id)
    thework.status = "executed"
    thework.save()
    for member in thework.worker.all():
	member.hoursworked+=thework.hours
	member.save()

    theworks = MemberWork.objects.filter(status='planned')
    return render(request,
		  TEMPLATEPREFIX+'memberswork_admin.html',
		  {'theworks':theworks,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})

@user_passes_test(thisclub_admin,login_url="/cvkbrno/login")
def members_work_delete_view(request,id=0):
    thework = MemberWork.objects.get(id=id)
    thework.delete()
    
    theworks = MemberWork.objects.filter(status='planned')
    return render(request,
		  TEMPLATEPREFIX+'memberswork_admin.html',
		  {'theworks':theworks,
		   'thisclub_admin':thisclub_admin(request.user),
		   'worked_hours':Member.objects.get(user=request.user).hoursworked,})

@user_passes_test(thisclub_member,login_url="/cvkbrno/login")
def members_work_addme(request,id,message="",successmessage=""):
    thework = MemberWork.objects.get(id=id)
    themember = Member.objects.get(user=request.user)
    thework.worker.add(themember)

    url = reverse(base_view)
    return HttpResponseRedirect(url)

@user_passes_test(thisclub_member,login_url="/cvkbrno/login")
def members_work_removeme(request,id,message="",successmessage=""):
    thework = MemberWork.objects.get(id=id)
    themember = Member.objects.get(user=request.user)
    thework.worker.remove(themember)

    url = reverse(base_view)
    return HttpResponseRedirect(url)


@user_passes_test(thisclub_member,login_url="/cvkbrno/login")
def makereservation_view(request,message="",successmessage=""):
    cleanoldreservations()
    member = Member.objects.get(user=request.user)
    activeoutings = Outing.objects.filter(rower=member,status="active")
    theboats = get_availableboats_reservation(member,timezone.now())
    # theboats = Boat.objects.filter(status__in = ["hangar", "water", "races"])
    if (len(activeoutings)!=0):
	# we are still out
	url = reverse(closeouting_view)
	return HttpResponseRedirect(url)
    if request.method == 'POST':
	# Form was submitted
	form = OutingReserveForm(request.POST)
	if form.is_valid():
	    # Get values from form
	    dist = request.POST['distance']
	    boat = Boat.objects.get(id=request.POST['boat'])
	    stime = request.POST['starttime']
	    sdate = request.POST['startdate']
	    etime = request.POST['endtime']
	    
	    starttime = parser.parse(sdate+' '+stime)
	    #starttime = timezone.make_aware(starttime)
	    starttime = LOCALTIMEZONE.localize(starttime)
	    
	    endtime = parser.parse(sdate+' '+etime)
	    #endtime = timezone.make_aware(endtime)
	    endtime = LOCALTIMEZONE.localize(endtime)
		
	    # check if conflicting reservations exist
	    check,errormessg = conflicting_reservations(boat,starttime,endtime)

	    if check:
		url = reverse(makereservation_view,
			      kwargs = {
				  'message':errormessg,
				  })

		return HttpResponseRedirect(url)
	    else:
		o = Outing(starttime=starttime,endtime=endtime,rower=member,
			   boat=boat,distance=dist,
			   status="reservation")
		o.save()
		# if not settings.DEBUG:
		#    logout(request)
		url = reverse(base_view)
		return HttpResponseRedirect(url)
	else:
	    return render(request, 
			  TEMPLATEPREFIX+'reservation_form.html',
			  {'form':form,
			   'theboats':theboats,
			   'reservations':get_future_reservations(),
			   'message':message,
			   'successmessage':successmessage,
			   'thisclub_admin':thisclub_admin(request.user),
			   'worked_hours':Member.objects.get(user=request.user).hoursworked,})
    
    else:
	nownaive = timezone.now().replace(tzinfo=None)
	nowlocal = timezone.now().astimezone(LOCALTIMEZONE)

	form = OutingReserveForm(
	    initial={'distance':11,
		     'starttime': nowlocal,
		     'startdate': nowlocal,
		     'endtime': nowlocal+datetime.timedelta(hours=1.5)}
	    )
	return render(request, 
		      TEMPLATEPREFIX+'reservation_form.html',
		      {'form':form,
		       'theboats':theboats,
		       'reservations':get_future_reservations(),
		       'message':message,
		       'successmessage':successmessage,
		       'thisclub_admin':thisclub_admin(request.user),
		       'worked_hours':Member.objects.get(user=request.user).hoursworked,})
    
    return HttpResponse(_("Make a reservation"))



@user_passes_test(thisclub_member,login_url="/cvkbrno/login")
def members_outing_delete_view(request,id):
    o = Outing.objects.get(id=id)
    o.delete()
    url = reverse(makereservation_view)
    return HttpResponseRedirect(url)

# functions

def addmemberwork(formdict):
    message = ""
    successmessage = ""
    id = 0
    date = formdict['date']
    name = formdict['name']
    comment = formdict['comment']
    worker = dict(formdict)['worker']
    hours = int(formdict['hours'])
    status = 'planned'
    thework = MemberWork(date=date,
			 hours=hours,
			 name=name,status=status,comment=comment)
    thework.save()
    if len(worker) != 0:
	for index in worker:
	    theworker = Member.objects.get(id=index)
	    thework.worker.add(theworker)
	thework.save()
	
    id = thework.id
    theview = members_work_admin_view
    successmessage = _("Members Work Created")
    message = ""

    # send email
    members = getclubmembers()
    bcclist = []
    for member in members:
	bcclist.append(member.user.email)

    print bcclist

    if settings.DEBUG:	    
	res = handle_sendemailwork.delay(bcclist,thework.name,
					 thework.date,thework.comment)

    else:
	res = queue.enqueue(handle_sendemailwork,bcclist,
			    thework.name,thework.date,thework.comment)

    
    return [theview,message,successmessage,id]

def addbulkboat(xlsfile):
    df = pd.read_excel(xlsfile)
    for index,row in df.iterrows():
	boatcode = df.ix[index,'code']
	boatname = smart_text(df.ix[index,'name'])
	nrseats = df.ix[index,'nrseats']
	status = 'hangar'
	cats = df.ix[index,'categories']
	cats = str(cats).split()
	print boatcode
	
	theboat = Boat(boatcode=boatcode,boatname=boatname,
		       nrseats=int(nrseats),
		       status=status)

	theboat.save()
	if (len(cats) !=0):
	    for index in cats:
		print index
		thecategory = BoatCategory.objects.get(id=index)
		print unidecode.unidecode(thecategory.name)
		theboat.categories.add(thecategory)

	theboat.save()


def addboat(formdict):
    message = ""
    successmessage = ""
    id = 0
    cats = dict(formdict)["categories"]
    boatcode = formdict['boatcode']
    boatname = formdict['boatname']
    nrseats = formdict['nrseats']
    status = formdict['status']
    comment = formdict['comment']
    theboat = Boat(boatcode=boatcode,boatname=boatname,
		   nrseats=int(nrseats),
		   status=status,comment=comment)
    # check if other boat exists with new code
    if len(Boat.objects.filter(boatcode=boatcode)) != 0:
	message = _("There is already a boat with that code")
	theview = boats_admin_add_view
	return [theview,message,"",id]
    else:
	theboat.save()
	
	if len(cats) !=0:
	    for index in cats:
		thecategory = BoatCategory.objects.get(id=index)
		theboat.categories.add(thecategory)

	theview = boats_admin_view
	successmessage = _('Boat created')
	message = ''
	return [theview,message,successmessage,id]

def editboat(formdict,theboat):
    # do something
    message = ""
    successmessage = ""
    theid = 0
    boatcode = formdict['boatcode']
    boatname = formdict['boatname']
    cats = dict(formdict)["categories"]
    nrseats = formdict['nrseats']
    status = formdict['status']
    comment = formdict['comment']
    theboat.boatname = boatname
    theboat.nrseats = nrseats
    theboat.status = status
    theboat.comment = comment
    theboat.categories.clear()
    theboat.save()
    if (len(cats) !=0):
	for index in cats:
	    thecategory = BoatCategory.objects.get(id=index)
	    theboat.categories.add(thecategory)

    # check if other boat exists with new code
    if boatcode != theboat.boatcode:
	if len(Boat.objects.filter(boatcode=boatcode)) != 0:
	    message = _("There is already a boat with that code")
	    theview = boats_admin_edit_view
	    theid = theboat.id
	    return [theview,message,"",theid]
	else:
	    theboat.boatcode = boatcode

    theboat.save()

    successmessage = _("Changes Saved")
    theview = boats_admin_view
    return [theview,"",successmessage,theid]

def addbulkmember(cats,xlsfile,sheetname):
    df = pd.read_excel(xlsfile,sheetname=sheetname)
    for index,row in df.iterrows():
	lastname,firstname = df.ix[index,'name'].split()
	email = df.ix[index,'e-mail']
	username = unidecode.unidecode(lastname)+unidecode.unidecode(firstname)[0]
	username = username.lower()
	password = 'cvkbrno'
	contributions = True
	hoursworked = 0
	status = 'member'

	print username
	
	theuser = User.objects.create_user(username,password=password)
	theuser.first_name = firstname
	theuser.last_name = lastname
	theuser.email = email
	theuser.save()

	themember = Member(user=theuser,status=status,
			   contributions=contributions,
			   hoursworked=hoursworked,
			   club=THISCLUB)

	themember.save()

	if (len(cats) !=0):
	    for index in cats:
		thecategory = BoatCategory.objects.get(id=index)
		themember.categories.add(thecategory)

	themember.save()

def addmember(formdict):
    message = ""
    successmessage = ""
    theid = 0
    theview = members_admin_view
    status = formdict['status']
    username = formdict['username']
    email = formdict['email']
    password = formdict['password']
    password2 = formdict['passwordconfirm']
    first_name = formdict['first_name']
    last_name = formdict['last_name']
    try:
	contributions = formdict['contributions']
    except:
	contributions = False
    hoursworked = formdict['hoursworked']
    cats = dict(formdict)["categories"]

    #check if passwords are equal
    if (password != password2):
	message = _("The two passwords are not equal")
	theview = members_admin_add_view
	theid = 0
	return [theview,message,"",theid]
 
    #check if there isn't already a user with this username
    if len(User.objects.filter(username=username)) != 0:
	    message = _("There is already a user with that username")
	    theview = members_admin_add_view
	    theid = 0
	    return [theview,message,"",theid]
    else:

	theuser = User.objects.create_user(username,password=password)
	theuser.first_name = first_name
	theuser.last_name = last_name
	theuser.email = email
	theuser.save()

	themember = Member(user=theuser,status=status,
			   contributions=contributions,
			   hoursworked=hoursworked,
			   club=THISCLUB)

	themember.save()

	if (len(cats) !=0):
	    for index in cats:
		thecategory = BoatCategory.objects.get(id=index)
		themember.categories.add(thecategory)

	themember.save()

	successmessage = _("New Member Created")
    
	return [theview,"",successmessage,theid]

def editmemberwork(formdict,thework):
    message = ""
    successmessage = ""
    theid = thework.id
    theview = members_work_admin_view
    name = formdict['name']
    date = formdict['date']
    comment = formdict['comment']
    workers = dict(formdict)["worker"]
    hours = formdict['hours']

    thework.date = date
    thework.name = name
    thework.hours = hours
    thework.comment = comment
    thework.save()

    if (len(workers) != 0):
	for index in workers:
	    theworker = Member.objects.get(id=index)
	    thework.worker.add(theworker)

    thework.save()
    successmessage = _("Members Work Updated")

    return [theview,"",successmessage,0]

def editmember(formdict,themember):
    message = ""
    successmessage = ""
    theid = themember.id
    theview = members_admin_view
    status = formdict['status']
    first_name = formdict['first_name']
    last_name = formdict['last_name']
    try:
	contributions = formdict['contributions']
    except:
	contributions = False
    hoursworked = formdict['hoursworked']
    cats = dict(formdict)["categories"]
    email = formdict['email']

    themember.status = status
    themember.contributions = contributions
    themember.hoursworked = hoursworked
    themember.categories.clear()

    if (len(cats) !=0):
	for index in cats:
	    thecategory = BoatCategory.objects.get(id=index)
	    themember.categories.add(thecategory)

    themember.save()

    

    theuser = themember.user
    theuser.first_name = first_name
    theuser.last_name = last_name
    theuser.email = email
    theuser.save()

    successmessage = _("Changes saved")

    return [theview,"",successmessage,0]


