#!/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 as 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('\n\n\n#ifndef MPS_FAULT_NUMBERS_H', file=outfile)
    print('#define MPS_FAULT_NUMBERS_H', file=outfile)
    print('#define GET_DEVICE_STATE_FOR(_fn)  ((*(bypassActiveBuffer + (_fn))) ? (*(bypassValueBuffer + (_fn))) : (*(latchedDeviceStateBuffer + (_fn))))', file=outfile)
    print('\n\n\n', file=outfile)

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

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

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

    if number_of_epics_faults > 0:

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

        epicsFaultBase = results['fault_number']

    else:
        epicsFaultBase = 0

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


    #     
    # Export indices
    #
    print('\n\n\n', file=outfile)
    print('/****************************************************************************************', file=outfile)
    print(' * Indices', file=outfile)
    print(' ***************************************************************************************/\n', file=outfile)
    

    currentFaultPrefix = ''
    for group in groups:
        print('\n/* {0[comment]} */'.format(group), file=outfile)
        try:
            cursor.execute(group['query'])
        except Exception as e:
            print(e)
        for row in cursor:
            if group['isLinkNodeFault']:
                baseFaultName = '_'.join((row['device_name'], row['base_fault_name'], 'BASE__INDEX'))
                if currentFaultPrefix != baseFaultName:
                    #print('#define', baseFaultName.ljust(colWidth['full_fault_name']), colpad, file=outfile)
                    #print('(  {0:6}  )'.format(row['fault_number']), file=outfile)
                    #print(file=outfile)
                    print(f"#define {baseFaultName.ljust(colWidth['full_fault_name'])}{colpad} (  {row['fault_number']:6}  )", file=outfile)
                    currentFaultPrefix = baseFaultName
            if isinstance(row['device_name'], bytes):
                dev_name = row['device_name'].decode('utf-8')
            else:
                dev_name = row['device_name']
            if isinstance(row['fault_name'], bytes):
                f_name = row['fault_name'].decode('utf-8')
            else:
                f_name = row['fault_name']

            defineIndexName = '_'.join((dev_name, f_name, '_INDEX'))
            #print('#define', defineIndexName.ljust(colWidth['full_fault_name']), colpad, file=outfile)
            #print('(  {0:6}  )'.format(row['fault_number']), file=outfile)
            print(f"#define {defineIndexName.ljust(colWidth['full_fault_name'])}{colpad} (  {row['fault_number']:6}  )", file=outfile)



    #     
    # Names
    #
    print('\n\n\n', file=outfile)
    print('/****************************************************************************************', file=outfile)
    print(' * Names', file=outfile)
    print(' ***************************************************************************************/\n', file=outfile)
    
    for group in groups:
        print('\n/* {0[comment]} */'.format(group), file=outfile)
        try:
            cursor.execute(group['query'])
        except Exception as e:
            print(e)
        for row in cursor:
            if isinstance(row['device_name'], bytes):
                dev_name = row['device_name'].decode('utf-8')
            else:
                dev_name = row['device_name']
            if isinstance(row['fault_name'], bytes):
                f_name = row['fault_name'].decode('utf-8')
            else:
                f_name = row['fault_name']
            defineName = '_'.join((dev_name, f_name))
            defineIndexName = ''.join((defineName, '__INDEX'))
            #print('#define', defineName.ljust(colWidth['full_fault_name']), colpad, file=outfile)
            #print('GET_DEVICE_STATE_FOR( ', defineIndexName.ljust(colWidth['full_fault_name']), ' )', file=outfile)
            print(f"#define {defineName.ljust(colWidth['full_fault_name'])}{colpad} GET_DEVICE_STATE_FOR( {defineIndexName.ljust(colWidth['full_fault_name'])} )", file=outfile)

    #     
    # States
    #
    print('\n\n\n', file=outfile)
    print('/****************************************************************************************', file=outfile)
    print(' * States', file=outfile)
    print(' ***************************************************************************************/\n', file=outfile)

    for group in groups:
        print('\n/* {0[comment]} */'.format(group), file=outfile)
        try:
            cursor.execute(group['query'])
        except Exception as e:
            print(e)
        for row in cursor:
            if isinstance(row['device_name'], bytes):
                dev_name = row['device_name'].decode('utf-8')
            else:
                dev_name = row['device_name']
            if isinstance(row['fault_name'], bytes):
                f_name = row['fault_name'].decode('utf-8')
            else:
                f_name = row['fault_name']
            defineName = '_'.join((dev_name, f_name))

            if isinstance(row['faulted_state_name'], bytes):
                f_s_name = row['faulted_state_name'].decode('utf-8')
            else:
                f_s_name = row['faulted_state_name']

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

            #print('#define', faulted_name.ljust(colWidth['full_fault_name_with_state']), colpad, file=outfile)
            #print('(!( ', defineName.ljust(colWidth['full_fault_name']), ' ))', file=outfile)
            print(f"#define {faulted_name.ljust(colWidth['full_fault_name_with_state'])}{colpad} (!( {defineName.ljust(colWidth['full_fault_name'])} ))", file=outfile)

            #print('#define', ok_name.ljust(colWidth['full_fault_name_with_state']), colpad, file=outfile)
            #print('  ( ', defineName.ljust(colWidth['full_fault_name']), ' )', file=outfile)
            #print(file=outfile)
            print(f"#define {ok_name.ljust(colWidth['full_fault_name_with_state'])}{colpad}  ( {defineName.ljust(colWidth['full_fault_name'])} )", file=outfile)
    print('#endif', file=outfile)
    outfile.close()


