#!/usr/bin/env python
"""print summary of files produced by getIOCPVs script"""

#==============================================================
#
#  Abs:   show summary of files produced by getIOCPVs script
#
#  Name:  showIOCPVs
#
#  Rem:   show CSV output of PVs and PV values
#
# Usage:  showIOCPVs <ioc-node-name> <before_dir> <after_dir> <PV_Atribute>
#
# Output: Columns of PV names and values. 
#
#  Auth:  26-Feb-2009, W. Colocho
#  Rev:
#
#---------------------------------------------------
# Mods: (Latest to oldest)
#
#
#

import sys
import os
import fnmatch

__all__ = ['name_field_and_value', 'pv_info_from_files']


def name_field_and_value(caget1_line, dir_name, default_field_name='No Name'):
    """
    Return a list (name, field, value) from a line of a caGet1
    file.  If no field name is found in the line, the default
    field name will be used.    
    """
    name_partition = caget1_line.partition('.')
    name = name_partition[0]
    field_and_value = name_partition[2]
    
    field_partition = field_and_value.partition(' ')
    field = field_partition[0] or default_field_name
    field = dir_name + '_' + field
    value = field_partition[2]
    value = value.strip()

    return (name, field, value)
    
    
def pv_info_from_files(file_list):
    """
    Return a dictionary of lists of dictionaries filled with the
    contents of the provided list of caGet1 files.
    
    The returned dictionary has the following layout.
    
    {
        pv1: [{field1: value}, {field2: value}, ...], 
        pv2: [{field1: value}, {field2: value}, ...],
        ... 
    }
    """
    pv_info = {}
    for file_name in file_list:
        input_file = open(file_name,'r')

        for line in input_file:
            (name, field, value) = name_field_and_value(line, file_name[2:5])        
            if not name in pv_info:
                pv_info[name] = list()
            pv_info[name].append({field:value})
            
        input_file.close()
        
    return pv_info


def main():
    if len(sys.argv) == 4:
        pv_attribute = '*'
    if len(sys.argv) == 5:
        pv_attribute = sys.argv[4]
    if len(sys.argv) < 4:
        sys.stderr.write('Error:  Incorrect number of arguments.  Must provide an IOC hostname, and two directories names.\n')
        return 1
        
    ioc_hostname  = sys.argv[1]
    before_dir = './' + sys.argv[2] + '/'
    after_dir =  './' + sys.argv[3] + '/'

    file_name_pattern = '*' + ioc_hostname + '*' + pv_attribute + '*'
    
    file_name_list_before =  fnmatch.filter(os.listdir(before_dir), file_name_pattern)    
    file_name_list_after = fnmatch.filter(os.listdir(after_dir), file_name_pattern)

        
    file_name_list = [ before_dir + file_name for file_name in file_name_list_before]+ [after_dir + file_name for file_name in file_name_list_after]    
    pv_info = pv_info_from_files(file_name_list)

    
    # Find max column lengths
    column_length = {} 
    column_length['pvname'] = max(len(key) for key in pv_info.iterkeys())

    for field_value_dict_list in pv_info.itervalues():
        for dictionary in field_value_dict_list:
            field = dictionary.keys()[0]
            value = dictionary.values()[0]

            if field in column_length:
                current_max_value_length = column_length[field]
            else:
                current_max_value_length = 0
                
            column_length[field] = max(current_max_value_length, len(field), len(value))

    
    # Print column headers
    column_separator = ', '
    row = list()
    row.append('PV Name'.ljust(column_length['pvname']))
    
    first_pv = pv_info.items()[0]
    first_pv_field_and_value_dicts = first_pv[1]
    for dictionary in first_pv_field_and_value_dicts:
        field = dictionary.keys()[0]
        row.append(field.rjust(column_length[field]))
    print column_separator.join(row)
  
    # Print data
    for name, fields_and_values in sorted(pv_info.iteritems()):
        row = list()
        row.append(name.ljust(column_length['pvname']))
        for item in fields_and_values:
            field = item.keys()[0]
            value = item.values()[0]
            row.append(value.ljust(column_length[field]))
        print column_separator.join(row)

    return 0
        
        
if __name__ == '__main__':
    status = main()
    sys.exit(status)
    
