#!/usr/bin/env python

import sys
import os
import string
import sqlite3

from . import mpsconfigquery
from . import format

def export(cursor, path, verbose):
    """
    Write include file to path
    """

    if verbose:
        print 'Exporting mapping file to', path
    
    try:
        outfile = open(path, 'w')
    except IOError, e:
        sys.stderr.write('Could not open "{path}": {errstr}\n'.format(path=path, errstr=e.strerror))
        return 1
        

    colpad   = ' ' * 4
    colWidth = {}
    
    column_len = format.max_column_lengths(cursor)
    colWidth['full_fault_name'] = column_len['device_name'] + column_len['fault_name'] + len('__INDEX') + 6
    colWidth['full_fault_name_with_state'] = column_len['device_name'] + column_len['fault_name'] + column_len['state_name'] + 8


    groups = (
                {
                    'query'             : mpsconfigquery.link_processor_faults + ' order by fault_number',
                    'comment'           : 'Link Processor Faults',
                    'isLinkNodeFault'   : False
                },
                {
                    'query'             : mpsconfigquery.epics_faults + ' order by fault_number',
                    'comment'           : 'EPICS Faults',
                    'isLinkNodeFault'   : False
                },
                {
                    'query'             : mpsconfigquery.link_node_faults + ' order by fault_number',
                    'comment'           : 'Link Node Faults',
                    'isLinkNodeFault'   : True
                },
                {
                    'query'             : mpsconfigquery.link_node_channel_faults + ' order by fault_number',
                    'comment'           : 'Link Node Channel Faults',
                    'isLinkNodeFault'   : False
                },
            )


    #     
    # Export base values
    #
    print >> outfile, '\n\n\n#ifndef MPS_FAULT_NUMBERS_H'
    print >> outfile, '#define MPS_FAULT_NUMBERS_H'
    print >> outfile, '#define GET_DEVICE_STATE_FOR(_fn)  ((*(bypassActiveBuffer + (_fn))) ? (*(bypassValueBuffer + (_fn))) : (*(latchedDeviceStateBuffer + (_fn))))'
    print >> outfile, '\n\n\n'

    print >> outfile, '/****************************************************************************************'
    print >> outfile, ' * Base Fault Numbers'
    print >> outfile, ' ***************************************************************************************/\n'
    
    baseFaultNumberWidth = 60
    try:
        cursor.execute(mpsconfigquery.fault_count)
        results = cursor.fetchone()
    except sqlite3.Error, e:
        print 'export_snl_program:', e.args[0]
        sys.exit(1)

    numberOfFaults = results['count']
    
    print >> outfile, '#define FAULT_COUNT'     .ljust(baseFaultNumberWidth), '( {0} )'.format(numberOfFaults)
    print >> outfile, '#define FAULT_ARRAY_SIZE'.ljust(baseFaultNumberWidth), '( {0} )'.format(numberOfFaults + 1)
    
    
    try:
        cursor.execute(mpsconfigquery.epics_fault_count)
        results = cursor.fetchone()
    except sqlite3.Error, e:
        print 'export_snl_program:', e.args[0]
        sys.exit(1)

    number_of_epics_faults = results['count']
    
    print >> outfile, '#define EPICS_FAULT_COUNT'.ljust(baseFaultNumberWidth), '( {0} )'.format(number_of_epics_faults)

    try:
        cursor.execute(mpsconfigquery.epics_faults + ' order by fault_number')
        results = cursor.fetchone()
    except sqlite3.Error, e:
        print 'export_snl_program:', e.args[0]
        sys.exit(1)

    epicsFaultBase = results['fault_number']

    print >> outfile, '#define EPICS_FAULT_NUMBER_BASE'.ljust(baseFaultNumberWidth), '( {0} )'.format(epicsFaultBase)


    #     
    # Export indices
    #
    print >> outfile, '\n\n\n'
    print >> outfile, '/****************************************************************************************'
    print >> outfile, ' * Indices'
    print >> outfile, ' ***************************************************************************************/\n'
    

    currentFaultPrefix = ''
    for group in groups:
        print >> outfile, '\n/* {0[comment]} */'.format(group)
        cursor.execute(group['query'])
        for row in cursor:
            if group['isLinkNodeFault']:
                baseFaultName = '_'.join((row['device_name'], row['base_fault_name'], 'BASE__INDEX'))
                
                if currentFaultPrefix != baseFaultName:
                    print >> outfile, '#define', baseFaultName.ljust(colWidth['full_fault_name']), colpad,
                    print >> outfile, '(  {0:6}  )'.format(row['fault_number'])
                    print >> outfile
                    currentFaultPrefix = baseFaultName

            defineIndexName = '_'.join((row['device_name'], row['fault_name'], '_INDEX'))
            print >> outfile, '#define', defineIndexName.ljust(colWidth['full_fault_name']), colpad,
            print >> outfile, '(  {0:6}  )'.format(row['fault_number'])


    #     
    # Names
    #
    print >> outfile, '\n\n\n'
    print >> outfile, '/****************************************************************************************'
    print >> outfile, ' * Names'
    print >> outfile, ' ***************************************************************************************/\n'
    
    for group in groups:
        print >> outfile, '\n/* {0[comment]} */'.format(group)
        cursor.execute(group['query'])
        for row in cursor:
            defineName = '_'.join((row['device_name'], row['fault_name']))
            defineIndexName = ''.join((defineName, '__INDEX'))
            print >> outfile, '#define', defineName.ljust(colWidth['full_fault_name']), colpad,
            print >> outfile, 'GET_DEVICE_STATE_FOR( ', defineIndexName.ljust(colWidth['full_fault_name']), ' )'


    #     
    # States
    #
    print >> outfile, '\n\n\n'
    print >> outfile, '/****************************************************************************************'
    print >> outfile, ' * States'
    print >> outfile, ' ***************************************************************************************/\n'

    for group in groups:
        print >> outfile, '\n/* {0[comment]} */'.format(group)
        cursor.execute(group['query'])
        for row in cursor:
            defineName = '_'.join((row['device_name'], row['fault_name']))

            faulted_name = '_'.join((defineName, row['faulted_state_name']))
            ok_name = '_'.join((defineName, row['ok_state_name']))

            print >> outfile, '#define', faulted_name.ljust(colWidth['full_fault_name_with_state']), colpad,
            print >> outfile, '(!( ', defineName.ljust(colWidth['full_fault_name']), ' ))'

            print >> outfile, '#define', ok_name.ljust(colWidth['full_fault_name_with_state']), colpad,
            print >> outfile, '  ( ', defineName.ljust(colWidth['full_fault_name']), ' )'
            print >> outfile

    print >> outfile, '#endif'
    outfile.close()


