"""talltowers plot"""
import datetime

import pytz
import numpy as np
from pandas.io.sql import read_sql
import matplotlib.dates as mdates
from pyiem.plot import figure
from pyiem.util import get_autoplot_context, get_dbconn


def get_description():
    """Return a dict describing how to call this plotter"""
    desc = {}
    desc["data"] = True
    desc[
        "description"
    ] = """This plot presents one second data from the
    Iowa Atmospheric Observatory Tall-Towers sites overseen by Dr Gene Takle.
    The plot limits the number of times plotted to approximately 1,000 so to
    prevent web browser crashes.  If you select a time period greater than
    20 minutes, you will get strided results."""
    desc["arguments"] = [
        dict(
            type="networkselect",
            name="station",
            default="ETTI4",
            label="Select Station",
            network="TALLTOWERS",
        ),
        dict(
            type="datetime",
            name="dt",
            default="2016/09/15 2340",
            label="Start Time (UTC Time Zone):",
            min="2016/04/01 0000",
        ),
        dict(
            type="int",
            name="minutes",
            default=10,
            label="Number of Minutes to Plot",
        ),
    ]
    return desc


def get_context(fdict):
    """Get plot context"""
    pgconn = get_dbconn("talltowers")
    ctx = get_autoplot_context(fdict, get_description())
    ctx["dt"] = ctx["dt"].replace(tzinfo=pytz.UTC)
    dt = ctx["dt"]
    station = ctx["station"]
    minutes = ctx["minutes"]
    # We can't deal with thousands of datapoints on the plot, so we stride
    # appropriately with hopes of limiting to 1000 x points
    size = minutes * 60.0
    stride = 1 if size < 1000 else int(((size / 1000) + 1))

    towerid = ctx["_nt"].sts[station]["remote_id"]
    ctx["title"] = "Tall Tower %s" % (ctx["_nt"].sts[station]["name"],)

    ctx["df"] = read_sql(
        """
        WITH data as (
            SELECT *, row_number() OVER (ORDER by valid ASC)
            from data_analog where tower = %s and
            valid between %s and %s ORDER by valid ASC)
        select * from data where row_number %% %s = 0
    """,
        pgconn,
        params=(towerid, dt, dt + datetime.timedelta(minutes=minutes), stride),
        index_col="valid",
    )
    return ctx


def highcharts(fdict):
    """Do highcharts variant"""
    ctx = get_context(fdict)
    df = ctx["df"]
    df["ticks"] = df.index.values.view(np.int64) // 10 ** 6
    lines = []
    lines2 = []
    lines3 = []
    lines4 = []
    for col in [
        "ws_5m_s",
        "ws_5m_nw",
        "ws_10m_s",
        "ws_10m_nwht",
        "ws_20m_s",
        "ws_20m_nw",
        "ws_40m_s",
        "ws_40m_nwht",
        "ws_80m_s",
        "ws_80m_nw",
        "ws_120m_s",
        "ws_120m_nwht",
    ]:
        vals = df[["ticks", col]].to_json(orient="values")
        lines.append(
            """{
            name: '"""
            + col
            + """',
            type: 'line',
            tooltip: {valueDecimal: 1},
            data: """
            + vals
            + """
            }
        """
        )
    for col in [
        "airtc_5m",
        "airtc_10m",
        "airtc_20m",
        "airtc_40m",
        "airtc_80m",
        "airtc_120m_1",
        "airtc_120m_2",
    ]:
        vals = df[["ticks", col]].to_json(orient="values")
        lines2.append(
            """{
            name: '"""
            + col
            + """',
            type: 'line',
            tooltip: {valueDecimal: 1},
            data: """
            + vals
            + """
            }
        """
        )
    for col in [
        "rh_5m",
        "rh_10m",
        "rh_20m",
        "rh_40m",
        "rh_80m",
        "rh_120m_1",
        "rh_120m_2",
    ]:
        vals = df[["ticks", col]].to_json(orient="values")
        lines3.append(
            """{
            name: '"""
            + col
            + """',
            type: 'line',
            tooltip: {valueDecimal: 1},
            data: """
            + vals
            + """
            }
        """
        )
    for col in [
        "winddir_5m_s",
        "winddir_5m_nw",
        "winddir_10m_s",
        "winddir_10m_nw",
        "winddir_20m_s",
        "winddir_20m_nw",
        "winddir_40m_s",
        "winddir_40m_nw",
        "winddir_80m_s",
        "winddir_80m_nw",
        "winddir_120m_s",
        "winddir_120m_nw",
    ]:
        vals = df[["ticks", col]].to_json(orient="values")
        lines4.append(
            """{
            name: '"""
            + col
            + """',
            type: 'line',
            tooltip: {valueDecimal: 1},
            data: """