# Python imports
from datetime import datetime
import cgi

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

# LeakLess Monitor imports
from Applications.Measure.models import LldevicePdlagAlarm
from Applications.Users.views import user_get_language, user_get_information
from Applications.Notifications.views import notification_return_list

def alarm_return_device_alarms(request):
    if request.user.is_authenticated():
        device_id   = request.GET.get('device_id')
        start_date  = datetime.strptime(request.GET.get('startDateInput'), "%Y-%m-%d %H:%M:%S")
        end_date    = datetime.strptime(request.GET.get('endDateInput'), "%Y-%m-%d %H:%M:%S")

        alarm_list=LldevicePdlagAlarm.objects.filter(timestamp__gte=start_date,timestamp__lte=end_date,lldevicelist=device_id)
        fmt = '%Y-%m-%d %H:%M:%S'
        html  = "<button style=\"margin-right: 20px; margin-top:-40px; color: #000000; font-size: 30px\" type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>"
        html += "<div style=\"margin-top: 50px;\"><table class=\"table table-striped\" id=\"tblGrid\">"
        html += "<thead id=\"tblHead\"><tr><th><font color=\"#444444\">Timestamp</font></th><th><font color=\"#444444\">Alarm</font></th></tr></thead><tbody>"
        for alarm in alarm_list:
            if alarm.checked is None:
                html += "<tr><td><font color=\"#444444\">"+alarm.timestamp.strftime(fmt)+"</font></td>"
                html += "<td><font color=\"#444444\">"+alarm.alarm+"</font</td></tr>"
            else:
                html += "<tr><td><font color=\"#444444\">"+alarm.timestamp.strftime(fmt)+"</font></td>"
                html += "<td><font color=\"#444444\">"+alarm.alarm+"</font</td></tr>"
        html += "</tbody></table></div>"
        return HttpResponse(html)
    else:
        return redirect(reverse('login_page'))



def alarm_confirm(request):
    if request.user.is_authenticated():
        try:
            LldevicePdlagAlarm.objects.filter(idlldevicepdlag_alarm=request.GET.get('AlarmID')).update(checked=1)
            return HttpResponse("Alarm confirmed")
        except Exception as e:
            return HttpResponse(e.message)
    else:
        return redirect(reverse('login_page'))


def alarm_return_alarm_notifications(request):
    if request.user.is_authenticated():
        permfield = []
        permissions = request.user.get_all_permissions()
        for perm in permissions:
            permfield.append(perm.split(".")[1])
        alarm_list = LldevicePdlagAlarm.objects.filter(lldevicelist__in=permfield, checked__isnull=True).order_by(
            '-timestamp')

        fmt = '%Y-%m-%d %H:%M:%S'
        counter = 0
        html = "<ul id=\"notifDropDown\" class=\"dropdown-menu scrollable-menu\" style=\"background-color: #3399cc;\" role=\"menu\">"
        for alarm in alarm_list:
            if counter == 10:
                break
            counter += 1
            html += "<li id=\"alarm" + str(alarm.idlldevicepdlag_alarm) + "\"><a><div><font color=\"#ffffff\">" + str(
                alarm.lldevicelist) + ", &#160; " + alarm.timestamp.strftime(
                fmt) + "&#160; &#160; <button type=\"button\" onclick=\"confirmAlarm(" + str(
                alarm.idlldevicepdlag_alarm) + ")\" class=\"btn btn-default\">Confirm</button><br><div align=\"center\">" + cgi.escape(
                alarm.alarm).replace(",", "<br>") + "</div>&#160;" + "</font></div></a></li>"
        html += "</ul>"
        if counter > 0:
            html = "<span id=\"redNotifier\" value=\"fire_Alarm\" class=\"badge badge-notify\">" + str(
                counter) + "</span>" + html
        else:
            html = "<span id=\"redNotifier\" class=\"badge badge-notify\"></span>" + html
        return HttpResponse(html)
    else:
        return redirect(reverse('login_page'))


def alarm_return_alarm_table(request):
    if request.user.is_authenticated():
        permfield=[]
        permissions=request.user.get_all_permissions()
        for perm in permissions:
            permfield.append(perm.split(".")[1])

        notification_list = notification_return_list(request)
        alarm_list=LldevicePdlagAlarm.objects.filter(lldevicelist__in=permfield)
        user_information=user_get_information(request)

        return render_to_response('alarms.html',{   'user_object'       : request.user,
                                                    'user_info'         : user_information,
                                                    'alarms'            : alarm_list,
                                                    'notification_list' : notification_list,
                                                    'lang'              :user_get_language(request)})
    else:
        return redirect(reverse('login_page'))


def alarm__render(request):
    if request.user.is_authenticated():
        device_id           = request.GET.get('device_id')
        device_identifier   = request.GET.get('device_identifier')

        device_parameters=LldevicePdlagParameters.objects.filter(lldevicelist=device_id)

        if len(device_parameters)!=1:
            return HttpResponse("Parameters not fetched!")

        last_parameter_change= device_parameters[0].lastparameterchange

        parameter_info=LldevicePdlagParameterinfo.objects.filter(visible__gte=1)

        alarm_parameters    = configuration_return_parameter_data(device_parameters[0], parameter_info, "ALARM")

        group_array=[{'name_cro': "Alarm"       , 'name_eng': "Alarm"   , 'param_list': alarm_parameters}]


        user_device_type                = user_get_device(request)


        return render_to_response('configuration.html',{'user_object'                       : request.user,
                                                        'user_device_type'                  : user_device_type,
                                                        'device_id'                         : device_id,
                                                        'device_identifier'                 : device_identifier,
                                                        'group_array'                       : group_array,
                                                        'lang'                              : user_get_language(request),
                                                        'last_parameter_change'             : last_parameter_change})
    else:
        return redirect(reverse('login_page'))