#!/usr/bin/python
# -*- coding: UTF-8 -*-


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, ExpDetail, PlotMeta, PlotData

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 = ExpDetail.objects(date=datetime.strptime(date, '%d-%m-%Y'))
    experiments = []
    
    for exp in exps:
        dum = {}
        dum['code'] = exp.experiment.code
        dum['plots'] = [plot.plot for plot in exp.plots()]
        dum['name'] = exp.experiment.name
        dt = datetime.now()
        
        t = time.mktime(dt.timetuple())

        if exp.plots()[0]['metadata']['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-exp['last_time']) > 10*60:
            status = 'Offline'
            clase = 'alertas-offline'
            style = 'danger'
            lastDataDate = exp['last_time']
        elif (t-exp['last_time']) > 5*60:
            status = 'Delayed'
            clase = 'alertas-delayed'
            style = 'warning'
            lastDataDate = exp['last_time']
        else:
            status = 'Online'
            clase = 'alertas-online'
            style = 'success'
            lastDataDate = exp['last_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))
    detail = ExpDetail.objects.get(experiment=exp, date=datetime.strptime(date, '%d-%m-%Y'))
    meta = PlotMeta.objects.get(exp_detail=detail, plot=plot)
    
    kwargs = {
        'code': code,
        'plot': plot,
        'date': date,
        'id': meta.pk,
        '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', {})

        