#!/usr/bin/python
# -*- coding: utf-8 -*-
# above encoding is for non-ascii in source comments

"""
Andy at FosteringCourtImprovement.org, 12/21/2011, version 1.0 release
WX Python GUI script reads multiple AFCARS files, sorts and classifies rows,
displays color-coded records in a search-enabled grid, saves to AFCARS file
with 2 added fields: 1. removal episode id, and 2. record class.

History:
abb 5/18/2012: crashing bc I didn't check for unicode in ExcessData, fixed, version 1.1.
abb 5/19/2012: epid format was %20.20s, should be %21.21s, fixed, version 1.1.
abb 5/24/2016: IL parsing errors bug fix, version 1.2
abb 12/7/2016: TN bug from added fields in afcarslinker1p2_data.py, version 1.2
abb 12/16/2016: PySimpleApp deprecated, use wx.App(False)
abb 11/7/2023: add remdate & plcdate to sort

"""

import os, sys
from afcarslinker1p2_data import *
buildgui = sys.stdout.isatty()

#===========================================================
# Command-line handlers:

# quicky function to output stats table:
def dict2txt( d1, h1=None, padchar=' ' ):
    if len(d1) > 0:
        padchar = ' '
        fw = map(len, h1) if h1 else [0]*len(d1)
        for v in d1.values():
            #v = d1.values()[0]
            fw = map( lambda i: max(fw[i], len(str(v[i]))), range(len(v)) )

        i = max(map( len, d1.keys() ))
        fw = [i]+fw
        pad = padchar * 2
        t1 = pad.join(map( lambda i: str((['']+list(h1))[i]).ljust(fw[i],padchar), range(len(fw)) ))
        for k, v in sorted(d1.items()):
            t1 += '\n'+pad.join(map( lambda i: str(([k]+list(v))[i]).rjust(fw[i],padchar), range(len(fw)) ))
    else:
        t1 = 'No valid records in files?'

    return( t1 )

def LinkAlert( d1 ):
    # check if any of the just-opened files link to prior files at less than 20%.
    if d1.filestats:
        fs2 = d1.filestats.ToPct()
        if len(fs2) > 1 and d1.filenames:
            for fn in reversed(sorted(fs2.keys())[1:]):
                if fn in d1.filenames and fs2[fn][FileStats.ilinks2prior] < 20:
                    print >> sys.stderr, 'WARNING: Links in '+fn+' < 20%.'

d1 = AFCARSFCDatafile()

"""
"""

if sys.argv and len(sys.argv) > 1 :
    # read in files from command line ...
    for filename in sys.argv[1:len(sys.argv)] :
        d1.ReadFile( filename, updatefunc )

#print >> sys.stderr, sys.stdout, sys.stdout.isatty(), sys.stderr
if buildgui:
    # Not piping stdout to file:
    # Make a wxgrid to display 2-d data as a table.
    from afcarslinker1p2_gui import *
    app = wx.App(False)
    app.TopWindow = DataFrame()
    app.TopWindow.SetDatafile( d1 )
    #app.TopWindow.Maximize()  # only want to maximize horiz, do it in _init_
    app.TopWindow.Show()
    if sys.argv and len(sys.argv) > 1 :
        app.TopWindow.UpdateValues()
        app.TopWindow.LinkAlert( d1.filenames )
    else:
        # no files on command line, so start with open file dialog.
        app.TopWindow.OnOpenFile()
    app.MainLoop()
else:
    d1.Sort()
    d1.ClassifyRows()
    LinkAlert( d1 )
    d1.SaveFile( 'stdout', updatefunc )
    print >> sys.stderr, dict2txt( d1.filestats, list(FileStats.colnames) )

"""
# Uncomment for windows build:
"""
from afcarslinker1p2_gui import *
app = wx.App(False)
app.TopWindow = DataFrame()
app.TopWindow.SetDatafile( d1 )
app.TopWindow.Show()
app.TopWindow.OnOpenFile()
app.MainLoop()
