# Python imports
from datetime import datetime, timedelta

# Django imports
from django.shortcuts import redirect
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, render, redirect
from django.template import RequestContext

# LeakLess Monitor imports
from Applications.Notifications.models import Lldevicenoatifications, Lldevicenoatificationsack
from Applications.Users.models import AuthUser
from Applications.Notifications.forms import NewNotificationForm

# Front end functions

def notification_accept(request):
    if request.user.is_authenticated():
        notification_ids=request.GET.get('notification_ids')
        notification_ids_list=filter(None, notification_ids.split(','))

        for notification in notification_ids_list:
            notification_id=int(notification)
            if notification_id is None:
                continue
            notification_data = Lldevicenoatifications.objects.get(idlldevicenoatifications=notification_id)
            user_data = AuthUser.objects.get(id=request.user.id)
            notification_accept_record = Lldevicenoatificationsack(userid=user_data, noatificationid=notification_data)
            notification_accept_record.save()

        return HttpResponse('Ok')
    else:
        return redirect(reverse('login_page'))


# Backend functions

def notification_return_list(request):
    user_id = request.user.id
    language_string = request.session.get('lang', 'en-gb')

    current_date = datetime.now()

    notifications_acknowledged = Lldevicenoatificationsack.objects.filter(userid=user_id)
    notifications_acknowledged_list = notifications_acknowledged.values_list('noatificationid', flat=True)

    # skip acknowledged notification
    notification_data_all = Lldevicenoatifications.objects.filter(expirationdate__gte=current_date)
    notification_data_excluded = notification_data_all.exclude(idlldevicenoatifications__in = notifications_acknowledged_list)

    return_data_notifications_not_acknowledged = []
    return_data_notifications_all = []

    for notification in notification_data_all:

        notification_info = {
            'id': notification.idlldevicenoatifications,
            'type': notification.type,
            'icon': notification.icon
        }

        if language_string == "hr":
            if notification.text_hr is None and notification.title_hr is None and notification.header_hr is None:
                notification_info['text'] = notification.text_en
                notification_info['title'] = notification.title_en
                notification_info['header'] = notification.header_en
            else:
                notification_info['text'] = notification.text_hr
                notification_info['title'] = notification.title_hr
                notification_info['header'] = notification.header_hr
        elif language_string == "en-gb":
            if notification.text_en is None and notification.title_en is None and notification.header_en is None:
                notification_info['text'] = notification.text_hr
                notification_info['title'] = notification.title_hr
                notification_info['header'] = notification.header_hr
            else:
                notification_info['text'] = notification.text_en
                notification_info['title'] = notification.title_en
                notification_info['header'] = notification.header_en

        return_data_notifications_all.append(notification_info)
        if notification in notification_data_excluded:
            return_data_notifications_not_acknowledged.append(notification_info)

    return_data = {
        'not_acknowledged': return_data_notifications_not_acknowledged,
        'all': return_data_notifications_all
    }

    return return_data

def notification_return_new_form(request):
    if request.method == 'POST':
        # Ovdje je upis u bazu

        form = NewNotificationForm(request.POST)

        notification_record = Lldevicenoatifications()

        if form.is_valid():
            valid_en = form.cleaned_data['valid_eng']
            valid_cro = form.cleaned_data['valid_cro']

            if valid_cro is False and valid_en is False:
                return HttpResponse('Error')
            if valid_en:
                notification_record.header_en = form.cleaned_data['header_eng']
                notification_record.title_en = form.cleaned_data['title_eng']
                notification_record.text_en = form.cleaned_data['text_eng']
            else:
                notification_record.header_en =None
                notification_record.title_en = None
                notification_record.text_en = None

            if valid_cro:
                notification_record.header_hr =form.cleaned_data['header_cro']
                notification_record.title_hr = form.cleaned_data['title_cro']
                notification_record.text_hr = form.cleaned_data['text_cro']
            else:
                notification_record.header_hr =None
                notification_record.title_hr = None
                notification_record.text_hr = None



            notification_record.type = form.cleaned_data['notification_type']
            notification_record.icon = form.cleaned_data['notification_icon']

            notification_valid = form.cleaned_data['notification_valid']
            creation_date= datetime.now()
            expiration_date = creation_date+timedelta(notification_valid)
            notification_record.creationdate=creation_date
            notification_record.expirationdate=expiration_date

            notification_record.save()

            return HttpResponse('Ok')
        else:
            return HttpResponse('Error')
    else:
        # Ovdje je dohvat iz baze

        form = NewNotificationForm()

        fields = list(form)
        form_general = fields[0:3]
        form_cro     = fields[3:7]
        form_eng     = fields[7:11]



        # Render list page with the documents and the form
    return render_to_response(
        'newNotificationForm.html',{  'form_general'      : form_general,
                                      'form_cro'          : form_cro,
                                      'form_eng'          : form_eng},
        context_instance=RequestContext(request)
    )