# Python imports
from datetime import datetime
import json, copy

# Django imports
from django.http import JsonResponse
from django.shortcuts import render
from django.template.loader import render_to_string

# LeakLess Monitor imports
from Applications.Measure.models import LldevicePdlagMeasure, Lldeviceannotations
from Applications.Measure.views import *
from Applications.Devices.views import devices_return_channel_labels
from Applications.Users.views import user_get_device, user_get_information



def tracking_view(request):
    if request.user.is_authenticated():

        device_list=Lldevicelist.objects.filter(loc_active=1)
        devices_treeview=[]


        for device in device_list:
            if request.user.has_perm("DeviceList."+str(device.id)):
                devices_treeview.append(tracking_return_device_node(device))

        user_information=user_get_information(request)
        user_device_type=user_get_device(request)
        return render_to_response('tracking.html',{ 'user_object'           : request.user,
                                                    'user_info'             : user_information,
                                                    'user_device_type'      : user_device_type,
                                                    'devices_treeview'      : json.dumps(devices_treeview),
                                                    'lang'                  : user_get_language(request)})
    else:
        return HttpResponse('Invalid user')


def tracking_return_device_node(device):
    device_id = str(device.id)
    device_identifier = "Unknown"
    if device.rem_identifier is not None:
        device_identifier = device.rem_identifier

    if device.loc_type == 'PDL-AG':
        return_data={
            'text'              : device_id+" ["+device_identifier+"]",
            'icon'              : "glyphicon glyphicon-stop",
            'selectedIcon'      : "glyphicon glyphicon-stop",
            'showCheckbox'      : False,
            #'color'             : "#000000",
            'backColor'         : "white",
            #'href'             : "#node-1",
            'selectable'        : False,
            'state': {
                'checked'       : True,
                'disabled'      : False,
                'expanded'      : False,
                'selected'      : False
            },
            #'tags'              : [device_identifier],
            'nodes'             : tracking_return_measurement_nodes_pdlag(device_id)
        }
    elif device.loc_type == 'MAG8000':
        return_data={
            'text'              : device_id+" ["+device_identifier+"]",
            'icon'              : "glyphicon glyphicon-stop",
            'selectedIcon'      : "glyphicon glyphicon-stop",
            'showCheckbox'      : False,
            #'color'             : "#000000",
            'backColor'         : "white",
            #'href'             : "#node-1",
            'selectable'        : False,
            'state': {
                'checked'       : True,
                'disabled'      : True,
                'expanded'      : False,
                'selected'      : False
            },
            'tags'              : ['N/A'],
            'nodes'             : tracking_return_measurement_nodes_mag8000(device_id)
        }
    else:
        return_data={}

    return return_data

def tracking_return_measurement_nodes_pdlag(device_id):
    return_data=[]
    node_info={
        'text'              : "Unknown",
        'icon'              : "glyphicon glyphicon-stop",
        'selectedIcon'      : "glyphicon glyphicon-stop",
        #'color'             : "#000000",
        'selectable '       : True,
        'state': {
            'checked'       : False,
            'disabled'      : False,
            'expanded'      : False,
            'selected'      : False
        },
        'tags'              : ['available']
    }

    channel_labels = devices_return_channel_labels(device_id)

    node_info_ch1_pressure=node_info.copy()
    node_info_ch1_pressure['text'] = 'CH1 Pressure ('+channel_labels['ch1_pressure_label']+')'
    return_data.append(node_info_ch1_pressure)

    node_info_ch2_pressure=node_info.copy()
    node_info_ch2_pressure['text'] = 'CH2 Pressure ('+channel_labels['ch2_pressure_label']+')'
    return_data.append(node_info_ch2_pressure)

    node_info_ch1_flow=node_info.copy()
    node_info_ch1_flow['text'] = 'CH1 Flow ('+channel_labels['ch1_flow_label']+')'
    return_data.append(node_info_ch1_flow)

    node_info_ch2_flow=node_info.copy()
    node_info_ch2_flow['text'] = 'CH2 Flow ('+channel_labels['ch2_flow_label']+')'
    return_data.append(node_info_ch2_flow)

    return return_data


def tracking_return_measurement_nodes_mag8000(device_id):
    return_data=[]
    return return_data

def tracking_return_data(request):
    if request.user.is_authenticated():
        if request.is_ajax():
            if request.method == 'POST':
                data_response = {}
                return_data =json.loads(request.body)

                for data in return_data:
                    data_start_date     = datetime.strptime(data['start_time'], "%Y-%m-%d %H:%M:%S")
                    data_end_date       = datetime.strptime(data['end_time'], "%Y-%m-%d %H:%M:%S")
                    data_device_id      = data['device_id']
                    measurement_list    = LldevicePdlagMeasure.objects.filter(
                        timestamp__gt=data_start_date, timestamp__lte=data_end_date,
                        lldevicelist=data_device_id).order_by('timestamp')

                    data_array=[]
                    if (not measurement_list):
                        continue
                    else:
                        min_time=measurement_list[0].timestamp
                        max_time=min_time


                    for measurement in measurement_list:
                        if (measurement.timestamp<min_time):
                            min_time=measurement.timestamp
                        if (measurement.timestamp>max_time):
                            max_time=measurement.timestamp

                        time=str(measurement.timestamp).replace("-", "/")
                        data_array.append([time,
                                           tracking_check_is_none(measurement.ch1_pressure),
                                           tracking_check_is_none(measurement.ch2_pressure),
                                           tracking_check_is_none(measurement.ch1_flow),
                                           tracking_check_is_none(measurement.ch2_flow),])
                    data_response[data_device_id]={
                        'data'      :   data_array,
                        'min_time'  :   str(min_time),
                        'max_time'  :   str(max_time)
                    }

                return JsonResponse(data_response)

            else:
                return_data =json.loads(request.GET)

    else:
        return HttpResponse('Invalid user')


def tracking_check_is_none(value):
    if value is None:
        value=0
    return value