#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals

import os
import time
from datetime import datetime

from django import forms
from django.contrib import messages
from django.utils.safestring import mark_safe
from django.shortcuts import render

import mongoengine

from plotter.models import Experiment, ExpMeta, ExpData

host = os.environ.get('HOST_MONGO', 'localhost')
mongoengine.connect('dbplots', host=host, port=27017)


# Forms
class SearchForm(forms.Form):

    experiment = forms.ChoiceField()
    plot = forms.ChoiceField()

    def __init__(self, *args, **kwargs):

        exp_choices = kwargs.pop('exp_choices', [])
        plt_choices = kwargs.pop('plt_choices', [])
        super(SearchForm, self).__init__(*args, **kwargs)
        self.fields['experiment'].choices = [(0, 'Select Experiment')] + exp_choices
        self.fields['plot'].choices = [(0, 'Select Plot')] + plt_choices
# we use this class to change the parameter in Scatter plot using the function plotly.restyle in jroplot.js
class ScatterSetupForm(forms.Form):
    
    plotdiv = forms.CharField(widget=forms.HiddenInput())
    ymax = forms.CharField(initial=30)
    ymin = forms.CharField(initial=10)

# we use this class to change the parameter in RTI plot using the function plotly.restyle in jroplot.js
class RTISetupForm(forms.Form):
    
    plotdiv = forms.CharField(widget=forms.HiddenInput())
    colormap = forms.ChoiceField(choices=[('Jet', 'Jet'), ('Viridis', 'Viridis'), ('RdBu', 'RdBu')])
    zmax = forms.CharField(initial=30)
    zmin = forms.CharField(initial=10)
    ymax = forms.CharField(initial=180)
    ymin = forms.CharField(initial=80)

# we use this class to change the parameter in SPC plot using the function plotly.restyle in jroplot.js
class SPCSetupForm(forms.Form):
    
    plotdiv = forms.CharField(widget=forms.HiddenInput())
    colormap = forms.ChoiceField(choices=[('Jet', 'Jet'), ('Viridis', 'Viridis'), ('RdBu', 'RdBu')])
    #como es un perfil xmin y xmax deben ser iguales a zmin y zmax
    xmax = forms.CharField(initial=30)
    xmin = forms.CharField(initial=10)
    #x2max = forms.CharField(initial=30)
    #x2min = forms.CharField(initial=10)
    ymax = forms.CharField(initial=180)
    ymin = forms.CharField(initial=80)
    zmax = forms.CharField(initial=30)
    zmin = forms.CharField(initial=10)

# Create your views here.
def main(request):
    
    kwargs = {}
    date = request.GET.get('date', datetime.now().strftime('%d/%m/%Y'))
    exps = ExpMeta.objects.filter(date=datetime.strptime(date, '%d/%m/%Y'))
    experiments = []
    
    for exp in exps:
        dum = {}
        dum['code'] = exp.code
        dum['plots'] = exp.plots
        dum['name'] = Experiment.objects.get(code=exp.code).name
        dt = datetime.now()
        data = ExpData.objects(expmeta=exp).order_by('-time')[0] #Get the time from the last data
        
        t = time.mktime(dt.timetuple())

        if exp['localtime'] == True: #Ask which type of time is coming: LT o UTC
            t -= 5*60*60
        # COnditionals to know which state are my clients
        if (t-data['time']) > 6*exp['interval']:
            status = 'Offline'
            clase = 'alertas-offline'
            style = 'danger'
            lastDataDate = data['time']
        elif (t-data['time']) > 3*exp['interval']:
            status = 'Delayed'
            clase = 'alertas-delayed'
            style = 'warning'
            lastDataDate = data['time']
        else:
            status = 'Online'
            clase = 'alertas-online'
            style = 'success'
            lastDataDate = data['time']

        dum['status'] = status
        dum['class'] = clase
        dum['style']= style
        dum['date']= datetime.utcfromtimestamp(lastDataDate)
        
        experiments.append(dum)
    
    kwargs['date'] = date
    kwargs['experiments'] = experiments
    
    return render(request, 'home.html', kwargs)


def plot(request, code=None, plot=None):
    '''
    '''

    realtime = False
    date = request.GET.get('date', None)
    if date is None:
        date = datetime.now().strftime('%d/%m/%Y')
        realtime = True
    exp = Experiment.objects.get(code=int(code))
    expmeta = ExpMeta.objects.get(code=int(code), date=datetime.strptime(date, '%d/%m/%Y'))
    
    kwargs = {
        'code': code,
        'plot': plot,
        'date': date,
        'id': expmeta.id,
        'realtime': realtime,
        'title': exp.name,
    }
    # Logic to show my views
    if plot == 'rti':
        kwargs['setup_form'] = RTISetupForm()
        kwargs['fn_plot'] = 'PcolorBuffer'
        kwargs['subtitle'] = 'RTI plot'
        return render(request, 'plot.html', kwargs)
    elif plot == 'spc':
        kwargs['setup_form'] = SPCSetupForm()
        kwargs['fn_plot'] = 'Pcolor'
        kwargs['subtitle'] = 'Spectra plot'
        return render(request, 'plot.html', kwargs)
    elif plot == 'noise':
        kwargs['setup_form'] = ScatterSetupForm()
        kwargs['fn_plot'] = 'Scatter'
        kwargs['subtitle'] = 'Noise plot'
        return render(request, 'plot.html', kwargs)
    else:
        return render(request, 'home.html', {})

        