#!/usr/bin/env python
# 
#  Copyright (C) 2004-2008,2010,2019  Smithsonian Astrophysical Observatory
#
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


import sys
import os
import subprocess

def load_data(infile):

    from pycrates import read_file
    tab = read_file(infile)

    def get_col(k):
        kcol = tab.get_column(k)
        k_vals = kcol.values.copy()
        k_name = kcol.name
        k_units = kcol.unit
        k_label = "{} [{}]".format(k_name, k_units)
        return k_vals, k_label

    x_vals,x_label = get_col(0)
    y_vals,y_label = get_col(1)

    import numpy as np
    good = np.isfinite(y_vals)
    good = np.logical_and(good, np.isfinite(x_vals))
    
    x_vals = x_vals[good]
    y_vals = y_vals[good]

    return x_vals,x_label,y_vals,y_label


def plot_data(access_point,x_vals, y_vals, title, x_label, y_label):
    
    cmd = ["xpaset", access_point, "plot", "new", "name", "dax",
           "{{{0}}}".format(title), 
           "{{{0}}}".format(x_label), 
           "{{{0}}}".format(y_label),
           "xy"
           ]
    xpa = subprocess.Popen( cmd, stdin=subprocess.PIPE ) 
    for x,y in zip(x_vals, y_vals):
        pair = "{} {}\n".format(x,y)
        pb = pair.encode()
        xpa.stdin.write(pb)        
    xpa.communicate()
    

def pretty_plot(access_point):
    def xpa_cmd( access_point, command ):
        cc = ["xpaset", "-p", access_point ]
        cc.extend( command.split(' '))    
        xpa = subprocess.Popen(cc)
        xpa.communicate()

    xpa_cmd(access_point, "plot view line no")
    xpa_cmd(access_point, "plot view step yes")
    xpa_cmd(access_point, "plot line step width 2")
        

if __name__ == '__main__':
    infile = sys.argv[1]
    title = sys.argv[2]
    access_point = sys.argv[3]

    x_vals,x_label,y_vals,y_label = load_data(infile)
    plot_data( access_point, x_vals, y_vals, title, x_label, y_label)
    pretty_plot(access_point)
    



