#!/usr/bin/env python

import sys
import os
import string
import sqlite3

from . import mpsconfigquery

module_dir = os.path.dirname(__file__)
template_dir = 'edm_templates'

def export(cursor, path, verbose):
    """
    Write EDM files to the folder specified by path
    """

    if verbose:
        print "Exporting EDM files to", path
    
    header_template_file_name = 'link_node_channel_header.txt'
    row_template_file_name = 'link_node_channel_row.txt'

    with open(os.path.join(module_dir, template_dir, header_template_file_name)) as f:
        contents = f.read()
        headerTemplate = string.Template(contents)
        
    with open(os.path.join(module_dir, template_dir, row_template_file_name)) as f:
        contents = f.read()
        rowTemplate = string.Template(contents)
    
    row_height = 16
    current_lnid = -1
    outfile = None
    
    # Find the number of channels for each link node
    link_node_channel_count = {}
    cursor.execute("select link_node_id, count(*) number_of_channels from link_node_channel_fault group by link_node_id")
    for row in cursor:
        link_node_channel_count[str(row['link_node_id'])] = row['number_of_channels']
    
    # Write out the files
    cursor.execute(mpsconfigquery.link_node_channel_faults + " order by link_node_id, card, channel")
    for row in cursor:
        if row['link_node_id'] != current_lnid:

            current_lnid = row['link_node_id']

            # Close current file
            if outfile:
                outfile.close()

            # Get the number of input channels for this link node
            number_of_channels = link_node_channel_count[str(row['link_node_id'])]
            window_size = 106 + number_of_channels * row_height
            box_size = 64 + number_of_channels * row_height

            # Open new file
            file_name = 'LinkNode{0}.edl'.format(row['link_node_id'])
            file_path = os.path.join(path, file_name)
            try:
                outfile = open(file_path, 'w')
            except IOError, e:
                sys.stderr.write('Could not open "%s": %s\n' % (file_path, e.strerror))
                return 1
            
            if verbose:
                print "Exporting", file_path
            
            # Print header
            print >> outfile, headerTemplate.substitute(linkNodeName = current_lnid, window_size = window_size, box_size = box_size)
            y = 68
                        
        pv_prefix = '%s:%s:%s:%s' % (row['pv_device_type'], row['pv_area'], row['pv_position'], row['pv_attribute'])
        # Print row
        print >> outfile, rowTemplate.substitute(y               = y,
                                                card             = row['card'],
                                                channel          = row['channel'],
                                                device_name      = pv_prefix, #row['device_name'],
                                                fault_name       = row['fault_name'],
                                                current_state_pv = pv_prefix + "_MPSC",
                                                latched_state_pv = pv_prefix + "_MPS",
                                                bypass_value_pv  = pv_prefix + "_BYPV",
                                                bypass_status_pv = pv_prefix + "_BYPS",
                                                unlatch_pv       = pv_prefix + "_UNLH",
                                                pv_prefix        = pv_prefix)    
        y += row_height

    outfile.close()
    export_epics_fault_edm_file(cursor, path, verbose)



def export_epics_fault_edm_file(cursor, path, verbose):
    """Write EDM file showing EPICS fault status to path"""

    header_template_file_name = 'epics_header.txt'
    row_template_file_name = 'epics_row.txt'

    with open(os.path.join(module_dir, template_dir, header_template_file_name)) as f:
        contents = f.read()
        headerTemplate = string.Template(contents)
        
    with open(os.path.join(module_dir, template_dir, row_template_file_name)) as f:
        contents = f.read()
        rowTemplate = string.Template(contents)

    row_height = 16

    # Open new file
    file_path = os.path.join(path, 'EPICSFaultInputs.edl')
    try:
        outfile = open(file_path, 'w')
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (file_path, e.strerror))
        return 1
    
    if verbose:
        print "Exporting", file_path
    
    # Find the number of epics faults
    cursor.execute("select count(*) count from epics_fault")
    count_of_channels = cursor.fetchone()
    
    if not count_of_channels:
        return 1    
    
    number_of_channels = int(count_of_channels['count'])
    window_size = 106 + number_of_channels * row_height
    box_size = 64  + number_of_channels * row_height
            
    # Print header
    print >> outfile, headerTemplate.substitute(window_size = window_size, box_size = box_size)
    y = 68

    # Write out the files
    cursor.execute(mpsconfigquery.epics_faults + " order by area, input_pv")
    for row in cursor:
        pv_prefix = '%s:%s:%s:%s' % (row['pv_device_type'], row['pv_area'], row['pv_position'], row['pv_attribute'])
        print >> outfile, rowTemplate.substitute(y                = y,
                                                 inputpv          = row['input_pv'],
                                                 device_name      = row['device_name'],
                                                 fault_name       = row['fault_name'],
                                                 current_state_pv = pv_prefix + "_MPSC",
                                                 latched_state_pv = pv_prefix + "_MPS",
                                                 bypass_value_pv  = pv_prefix + "_BYPV",
                                                 bypass_status_pv = pv_prefix + "_BYPS",
                                                 unlatch_pv       = pv_prefix + "_UNLH",
                                                 pv_prefix        = pv_prefix)    
        y += row_height
    
    outfile.close()


