#!/usr/bin/env python
from __future__ import print_function, division, unicode_literals
import os
from collections import OrderedDict

import numpy as np
import matplotlib.pyplot as plt

from hcam_widgets.globals import Container
from hcam_drivers.config import load_config
from hcam_drivers.hardware import meerstetter, vacuum
from astropy.time import Time
from astropy import units as u

if __name__ == "__main__":
    g = Container()
    g.cpars = dict()
    load_config(g)
    cpars = g.cpars

    gauges = [vacuum.PDR900(cpars['termserver_ip'], port) for port in cpars['vacuum_ports']]
    ms = [meerstetter.MeerstetterTEC1090(ip, 50000) for ip in cpars['meerstetter_ip']]

    plt.style.use('seaborn-colorblind')
    plt.ion()

    fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True)
    plt.subplots_adjust(wspace=0, hspace=0)
    pressure_ax = axes[0]
    temp_ax = axes[1]

    start = Time.now()

    xp = []
    pressures = OrderedDict()
    for ccd in ('1', '2', '3', '4', '5'):
        pressures[ccd] = []

    ccd_temps = OrderedDict()
    ccd_temps['1'] = (1, [])
    ccd_temps['2'] = (2, [])
    ccd_temps['3'] = (3, [])
    ccd_temps['4'] = (1, [])
    ccd_temps['5'] = (2, [])

    for ccd in pressures:
        y = pressures[ccd]
        pressure_ax.plot(xp, y, label='CCD{}'.format(ccd))
    for ccd in ccd_temps:
        y = ccd_temps[ccd][1]
        temp_ax.plot(xp, y, label='CCD{}'.format(ccd))

    pressure_ax.set_xlabel('Time (hours)')
    pressure_ax.set_ylabel('Pressure (mbar)')
    temp_ax.set_xlabel('Time (hours)')
    temp_ax.set_ylabel('Temp (deg C)')
    temp_ax.legend()
    pressure_ax.legend()

    if not os.path.exists('hw_log.txt'):
        with open('hw_log.txt', 'w') as log:
            log.write('# MJD, P1, P2, P3, P4, P5, T1, T2, T3, T4, T5\n')

    with open('hw_log.txt', 'a', buffering=1) as log:
        while True:
            x = Time.now()
            xp.append((x - start).to(u.hour).value)
            log.write('{}, '.format(x.mjd))

            for ccd in pressures:
                iccd = int(ccd) - 1
                try:
                    pressure = 1000*gauges[iccd].pressure.value
                except:
                    print('warning: failed to log pressure for ccd {}'.format(ccd))
                    pressure = np.nan
                pressures[ccd].append(pressure)
                log.write('{}, '.format(pressure))
                pressure_ax.lines[iccd].set_xdata(xp)
                pressure_ax.lines[iccd].set_ydata(pressures[ccd])

            for ccd in ccd_temps:
                iccd = int(ccd) - 1
                address, temp_array = ccd_temps[ccd]
                if iccd < 3:
                    meer = ms[0]
                else:
                    meer = ms[1]
                try:
                    temp = meer.get_ccd_temp(address).value
                except:
                    print('warning: failed to log temp for ccd {}'.format(ccd))
                    temp = np.nan
                temp_array.append(temp)
                log.write('{}, '.format(temp))
                temp_ax.lines[iccd].set_xdata(xp)
                temp_ax.lines[iccd].set_ydata(temp_array)

            log.write('\n')

            temp_ax.relim()
            pressure_ax.relim()
            temp_ax.autoscale_view()
            pressure_ax.autoscale_view()

            plt.pause(20)

    # keep plot around until quit
    while True:
        plt.pause(0.05)
