'''
Start.views - User interaction with Start page
'''
from django.core.urlresolvers import reverse
from django.views.decorators.cache import cache_control
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.template import Context, loader
from django.core.exceptions import MultipleObjectsReturned
from MyPidge.Users.models import User
from MyPidge.Start.models import StartLink
from MyPidge.Groups.models import GroupService, GroupServiceProperty, ServiceProperty
from MyPidge.Events.models import EventTime, Observance
from MyPidge.basic import MustLogin, MustLoginMessage
from datetime import datetime
from urllib import quote, urlopen

def StartPage(request):
    ''' Show start page '''
    flags = {}
    if request.session.get('loggedin') and request.session['loggedin']:
        flags['loggedin'] = True
    return render_to_response('start-start', {'activetab': 'Start', 'flags': flags})

def StartPageSettingsXML(request):
    ''' Set XML Cookie with User's Start settings '''

    # Our actual (non-cookie) output to the browser is unimportant as no user ever sees it
    r = HttpResponse("Done.")
    
    if request.session.get('loggedin'):
        user = User.objects.get(pk=request.session['userid'])
        r.set_cookie('spsettings', quote(generateSettingsString(user)))
    else:
        if request.session.get('raven-crsid'):
            r.set_cookie('spsettings', quote(generateDefaultSettingsString(raven = request.session['raven-crsid'])))
        else:
            r.set_cookie('spsettings', quote(generateDefaultSettingsString()))
    
    return r

@cache_control(must_revalidate=False, max_age=60*15)
def StartPageSettingsJS(request):
    ''' Return Javascript of Start page settings. '''
    if request.session.get('loggedin'):
        user = User.objects.get(pk=request.session['userid'])
        spsettings = generateSettingsString(user)
    else:
        spsettings = generateDefaultSettingsString()
    
    t = loader.get_template('start-settings-js')
    c = Context({'spsettings': quote(spsettings)})
    h = HttpResponse(t.render(c))
    h['Expires'] = "Fri, 16 Aug 2013 13:20:54 GMT"
    return h
    
    
def StartPageSearchDataXML(request):
    gsps = GroupServiceProperty.objects.filter(serviceproperty__display_on_group_page = True, serviceproperty__type='URL').distinct()
    gsparray={}
    for gsp in gsps:
        sname = gsp.GetLinkName()
        gsparray[gsp.id] = sname
        
    return render_to_response('start-search-data', {'gsps': gsps, 'gsparray': gsparray})


def generateDefaultSettingsString(raven = ""):
    ''' Returns XML of default start page settings.'''
    
    startlinks = StartLink.objects.filter(defaultlink__exact=True).order_by('id')

    return render_to_string('start-settings', {'startlinks': startlinks, 'openlinksinnew': True, 'opensearchinnew': False, 'showflagstatus': False, 'raven': raven})

# FIXME: Open link in new window needs to be implemented here and in the start page template
def generateSettingsString(usr):
    ''' Returns XML of user's start page settings.'''
    
    startlinks = usr.links.all().order_by('id')

    return render_to_string('start-settings', {'user': usr, 'startlinks': startlinks, 'openlinksinnew': usr.start_openlinksinnew, 'opensearchinnew': usr.start_opensearchinnew, 'showflagstatus': usr.start_showflagstatus})


@MustLogin
def CustomiseSearch(request):
    
    bc = [{'title': 'Start', 'url': reverse('homepage')},
        {'title': 'Customise Search Box'}]
    
    user = User.objects.get(id = request.session['userid'])
    
    flags = {}
    
    if request.method=='POST':
        if 'opensearchinnew' in request.POST:
            user.start_opensearchinnew = True
        else:
            user.start_opensearchinnew = False
        user.save()
        flags['saved'] = True
        
    return render_to_response('start-customise-search', {'breadcrumb': bc, 'activetab': 'Start', 'opensearchinnew': user.start_opensearchinnew, 'flags': flags})

@MustLoginMessage("You must become a MyPidge User in order to customise the site. ")
def Customise(request):
    ''' Show options to customise the start page. '''
    
    bc = [{'title': 'Start', 'url': reverse('homepage')},
        {'title': 'Customise Start Page'}]

    user = User.objects.get(id = request.session['userid'])
    
    flags = {}
    
    if 'what' in request.POST:
        user.links.clear()
        for linkbox in request.POST:
            if linkbox.startswith("link_"):
                user.links.add(StartLink.objects.get(pk=long(linkbox.lstrip('link_'))))
        
            
        if 'showflagstatus' in request.POST:
            user.start_showflagstatus = True
        else:
            user.start_showflagstatus = False
        
        user.save()
        flags['saved'] = True

    # Get all possible user links
    initUserLinks = user.GetAllLinks()
    linkshave = user.links.all()
    userLinks = []
    
    for link in initUserLinks:
        if link in linkshave: link.has = True
        userLinks.append(link)
    
    initPidgeLinks = StartLink.objects.GetPidgeLinks()
    pidgeLinks = []
    
    for link in initPidgeLinks:
        if link in linkshave: link.has = True
        pidgeLinks.append(link)

    gsps = GroupServiceProperty.objects.filter(groupservice__group__membership__person = user, serviceproperty__display_on_group_page = True, serviceproperty__type='URL').distinct()

    gsparray = {}
    for gsp in gsps:
        sname = gsp.GetLinkName()
        gsparray[gsp.id] = sname
    
    return render_to_response('start-customise', {'breadcrumb': bc, 'activetab': 'Start', 'pidgeLinks': pidgeLinks, 'userLinks': userLinks, 'flags': flags, 'opensearchinnew': user.start_opensearchinnew, 'gsps': gsps, 'gsparray': gsparray, 'showflagstatus': user.start_showflagstatus})
    
@MustLoginMessage("You must become a MyPidge User in order to add links to your homepage. ")
def AddGroupServiceLink(request, groupservicepropertyid, returnurl):
    ''' Add User's Group's web site and show Start customise page. '''
    
    bc = [{'title': 'Start', 'url': reverse('homepage')},
        {'title': 'Customise Start Page', 'url': reverse('MyPidge.Start.views.Customise')}]
    
    user = User.objects.get(id = request.session['userid'])
    
    try:
        gsp = GroupServiceProperty.objects.get(id=groupservicepropertyid)
        linkname = gsp.GetLinkName()
        url = gsp.value
        StartLink.objects.Add(user, linkname, url)
    except (GroupServiceProperty.DoesNotExist, ServiceProperty.DoesNotExist, MultipleObjectsReturned):
        pass
    
    return HttpResponseRedirect(returnurl + "?linkadded")
        

@MustLogin
def AddLink(request):
    ''' Show add link page. '''
    
    bc = [{'title': 'Start', 'url': reverse('homepage')},
        {'title': 'Customise Start Page', 'url': reverse('MyPidge.Start.views.Customise')},
        {'title': 'Add Link'}]
    
    user = User.objects.get(id = request.session['userid'])
    if request.method == "POST":
        alf = AddLinkForm(request.POST)
        if alf.is_valid():
            StartLink.objects.Add(user, alf.cleaned_data['name'], alf.cleaned_data['url'])
            return HttpResponseRedirect(reverse('MyPidge.Start.views.Customise'))
    else:
        alf = AddLinkForm(initial={'url':'http://'})

    return render_to_response("start-add-link", {'breadcrumb': bc, 'activetab': 'Start', 'addlinkform': alf.as_p()})    

    
@MustLogin
def DeleteLink(request, linkid):
    ''' Delete link from user's start page and refresh start customise page. '''
    
    bc = [{'title': 'Start', 'url': reverse('homepage')},
        {'title': 'Customise Start Page', 'url': reverse('MyPidge.Start.views.Customise')},
        {'title': 'Add Link'}]

    user = User.objects.get(id = request.session['userid'])
    try:
        lnk = StartLink.objects.get(id=linkid)
        user.links.remove(lnk)
        if lnk.owner == user:
            lnk.delete()
    except(StartLink.DoesNotExist):
        pass
    
    return HttpResponseRedirect(reverse('MyPidge.Start.views.Customise'))


class AddLinkForm(forms.Form):
    ''' Form for add link page '''
    name = forms.CharField(max_length=128)
    url = forms.URLField(label='Website Address')

def GetFlagStatus(request):
    try:
        u = urlopen("http://www.cucbc.org/flag.txt")
    except IOError:
        return HttpResponse("Not found")
    else:
        return HttpResponse(u.read())

def GetStartPageEvents(request):
    ''' Return XML of events. '''

    intevents = None

    if request.session.get('loggedin'):
        user = User.objects.get(id = request.session['userid'])
        intevents = EventTime.objects.filter(event__group__membership__person = user, finish__gte = datetime.now()).distinct().order_by('start')[:5]
    else:
        intevents = EventTime.objects.filter(finish__gte=datetime.now()).distinct().order_by('start')[:5]

    return render_to_response("start-events-xml", {'intevents': intevents})
