# -*- mode: python; coding: utf-8 -*-
# Copyright 2016 the HERA Collaboration
# Licensed under the 2-clause BSD license.

"""M&C logging of antenna autocorrelation powers.

These are key data for tracking antenna performance and failures.

"""

from __future__ import absolute_import, division, print_function

from math import floor
from astropy.time import Time
import numpy as np
import six
from sqlalchemy import BigInteger, Column, Float, Integer, String

from . import MCDeclarativeBase


allowed_measurement_types = ["median"]


class HeraAuto(MCDeclarativeBase):
    """
    Definition of median antenna autocorrelation table of hera antennas.

    Attributes
    ----------
    time : BigInteger Column
        The time in GPS seconds of the observation, floored as an int. Part of primary_key
    antenna_number : Integer Column
        Antenna number. Part of primary_key.
    antenna_feed_pol : String Column
        Feed polarization, either 'e' or 'n'. Part of primary_key.
    measurement_type : String Column
        The type of measurement.
        Currently available types: median
        Cannot be None.
    value : Float Columnn
        Cannot be None
    """

    __tablename__ = "hera_autos"

    time = Column(BigInteger, primary_key=True)
    antenna_number = Column(Integer, primary_key=True)
    antenna_feed_pol = Column(String, primary_key=True)
    measurement_type = Column(String, nullable=False)
    value = Column(Float, nullable=True)

    @classmethod
    def create(cls, time, antenna_number, antenna_feed_pol, measurement_type, value):
        """
        Create a new Autocorrelation table object.

        Parameters
        ----------
        time : astropy time object
            Astropy time object based on timestamp of autocorrelation.
        antenna_number : int
            Antenna Number
        antenna_feed_pol : str
            Feed polarization, either 'e' or 'n'.
        measurement_type : Int
            The measurment type of the autocorrelation.
            Currently supports: 'median'.
        value : float
            The median autocorrelation value as a float.

        """
        if not isinstance(time, Time):
            raise ValueError("time must be an astropy Time object.")
        auto_time = floor(time.gps)

        if antenna_feed_pol not in ["e", "n"]:
            raise ValueError("antenna_feed_pol must be 'e' or 'n'.")

        if not isinstance(measurement_type, six.string_types):
            raise ValueError("measurement_type must be a string")

        if measurement_type not in allowed_measurement_types:
            raise ValueError(
                "Autocorrelation type {0} not supported. "
                "Only the following types are supported: {1}"
                .format(measurement_type, allowed_measurement_types)
            )

        return cls(
            time=auto_time,
            antenna_number=antenna_number,
            antenna_feed_pol=antenna_feed_pol,
            measurement_type=measurement_type,
            value=value
        )


def plot_HERA_autocorrelations_for_plotly(session, offline_testing=False):
    if six.PY3:
        from plotly import graph_objects as go
    else:
        from plotly import graph_objs as go

    from chart_studio import plotly as py

    data = []
    all_autos = session.get_autocorrelation(most_recent=True)

    antennas = set(['{ant}{pol}'.format(ant=item.antenna_number, pol=item.antenna_feed_pol)
                    for item in all_autos])
    data = {}
    for ant in antennas:
        data[ant] = []
    for item in all_autos:
        key = '{ant}{pol}'.format(ant=item.antenna_number, pol=item.antenna_feed_pol)
        data[key].append([Time(item.time, format='gps').isot, item.value])
    scatters = []
    for ant in data:
        d = np.array(data[ant])
        scatters.append(go.Scatter(x=d[:, 0],
                                   y=d[:, 1],
                                   name=ant,
                                   ))

    # Finish plot

    layout = go.Layout(showlegend=True,
                       title='HERA Autocorrelations',
                       xaxis={'title': 'Date',
                              },
                       yaxis={'title': 'auto power',
                              },
                       )
    fig = go.Figure(data=scatters,
                    layout=layout,
                    )
    if offline_testing:
        return fig
    else:
        py.plot(fig, auto_open=False,
                filename='HERA_daily_autos',
                )

@@ -1457,19 +1457,20 @@
 ullable=
-Tru
+Fals
 e)%0A%0A    

revert value to no nullable