import datetime
import os

import dash_core_components as dcc
import dash_html_components as html
import plotly
import plotly.tools

from dash.dependencies import Input, Output
from pyorbital.orbital import Orbital

from app import app


SATELLITE = Orbital('TERRA')


layout = html.Div([
    html.H2("live updating components"),
    html.Div([
        html.H4('TERRA Satellite Live Feed'),
        html.Div(id='live-update-text'),
        dcc.Graph(id='live-update-graph'),
        dcc.Interval(
            id='interval-component',
            interval=5 * 1000, # in milliseconds
            n_intervals=0
        )
    ]),
])


# live updating components
@app.callback(
    Output('live-update-text', 'children'),
    [Input('interval-component', 'n_intervals')]
)
def update_metrics(n):
    lon, lat, alt = SATELLITE.get_lonlatalt(datetime.datetime.now())
    style = {'padding': '5px', 'fontSize': '16px'}
    return [
        html.Span('Longitude: {0:.2f}'.format(lon), style=style),
        html.Span('Latitude: {0:.2f}'.format(lat), style=style),
        html.Span('Altitude: {0:0.2f}'.format(alt), style=style)
    ]


@app.callback(
    Output('live-update-graph', 'figure'),
    [Input('interval-component', 'n_intervals')]
)
def update_graph_live(n):
    data = {
        _: [] for _ in ['time', 'Latitude', 'Longitude', 'Altitude', 'opacity']
    }
    # Collect some data
    for i in range(360):
        time = datetime.datetime.now() - datetime.timedelta(seconds=i * 20)
        lon, lat, alt = SATELLITE.get_lonlatalt(time)
        data['Longitude'].append(lon)
        data['Latitude'].append(lat)
        data['Altitude'].append(alt)
        data['time'].append(time)
        data['opacity'].append(2 ** -(i/180))

    # Create the graph with subplots
    fig = plotly.tools.make_subplots(
        rows=2, cols=1, vertical_spacing=0.2, print_grid=False
    )
    fig['layout']['margin'] = {'l': 30, 'r': 10, 'b': 30, 't': 10}
    fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'}

    fig.append_trace({
        'x': data['time'],
        'y': data['Altitude'],
        'name': 'Altitude',
        'mode': 'lines+markers',
        'type': 'scatter'
    }, 1, 1)
    fig.append_trace({
        'x': data['Longitude'],
        'y': data['Latitude'],
        'text': data['time'],
        'name': 'Longitude vs Latitude',
        'mode': 'markers',
        'type': 'scatter',
        'marker': {'opacity': data['opacity']},
    }, 2, 1)
    fig.append_trace({
        'x': data['Longitude'][:1],
        'y': data['Latitude'][:1],
        'text': data['time'],
        'name': 'Current Longitude and Latitude',
        'mode': 'markers',
        'type': 'scatter'
    }, 2, 1)

    return fig
