#!/usr/bin/env python

import argparse
import os
import re

import globals

# used to format data
IOCtype_list = []
alias_list = []
user_list = []
path_list = []
comment_list = []
header_list = []
empty_lines = []

# patterns
name = re.compile(r'[A-Za-z\d]+')
number = re.compile(r'\d+')
path = re.compile(r'/[A-Za-z\d\-_/]+')

# hard coding headers
bad_lines = ['#                        This is an input argument to iocConsole.py',
            '#                        ioc naming convention:>',
            '#                          hard ioc:',
            '#                             rtems:          ioc-<area>-<2-char subsystem><2-digit #>',
            '#                             cold-fire:      eioc-<area>-<2-char subsystem><2-digit#>',
            '#                             linuxRT         cpu-<area>-<2-char subsystem><2-digit #>',
            '#                          soft iocs:',
            '#                            linux (sioc):    sioc-<area>-<2-char subsystem><2-digit #>',
            '#                            linuxrt (vioc):  vioc-<area>-<2-char subsystem><2-digit #>',
            '#                        for soft ioc (sioc), this is the executable with absolute path',
            '#                        for soft ioc (vioc), this is the host screen is run on',
            '#                        for soft ioc (sioc), this is not used by the iocConsole.py.',
            '#                        for soft ioc (vioc), this is the host user account used to run screen',
            '#          All columns must be separated with a space " ", as in the example below',
            '#          Alias/IOC       TS/Path to binary    Port No.      Host screen is run   Description',
            '#          =======================================================================================',
            '#          ioc-li20-pm01   ts-li20-nw01           2001         <not used>',
            '#          cpu-ltu1-mg03   ts-b912-nw02           2002         <not used>          emcor cpu in ltu',
            '#          sioc-la20-ls21  <full path>/LaserSoft  <not used>    facet-daemon1',
            '#          Virtual IOC     Host                   User       Path to binary        Description',
            '#          vioc-ltu1-mg03  cpu-ltu1-mg03          laci      <full path>/mgntSoft   embedded COMx emcor ioc',
            '#           sioc-b15-gun1'
            ]

# establishes correct read and write file paths
def commandoptions():
    parser = argparse.ArgumentParser(description= 'Establishes a file to read from and file to write to')
    parser.add_argument('-r', '--read-file', required=True, help='Define what file data is read from, expects screeniocs file')
    parser.add_argument('-w', '--write-file', required=True, help='Define what file data is written to')

    args = parser.parse_args()

    screenIOCsFileName = args.read_file
    updatedScreenIOCsFileName = args.write_file

    return screenIOCsFileName, updatedScreenIOCsFileName

def processScreenIOCs(screenIOCsFileName):
    with open(screenIOCsFileName) as f:
        for line in f.read().splitlines():
            currentIOCInfo = {}
            trimmed_line = line.strip()

            if trimmed_line.startswith('#'):
                # hard coding header formats
                if "Fixed" in line and "Host where" in line:
                    currentIOCInfo['header'] = '# Type                      IOC user and host'
                elif "Port No." in line:
                    currentIOCInfo['header'] = '# HIOC   Alias              where screen is run    user, node, and port     Comments (must start with #)'
                elif "Host where" in line:
                    currentIOCInfo['header'] = '# Type                      IOC user and host      Terminal server'
                elif "-------      -------------" in line:
                    currentIOCInfo['header'] = '#-----   ---------------    -------------------    ----------------------   -----------------------------------------------'
                elif 'Executable, including path' in line:
                    currentIOCInfo['header'] = '# SIOC   Alias              where screen is run    Executable, including path'
                elif "-------  ---------------------------" in line:
                    currentIOCInfo['header'] = '#-----   ---------------    -------------------    --------------------------'
                elif "Computer Host" in line:
                    currentIOCInfo['header'] = '# VIOC   Alias              User and CPU host      Executable including path                                Description'
                elif '1st Column: ioc name or alias (e.g. ioc-as01-mg01,sioc-li21-mg01)' in line:
                    currentIOCInfo['header'] = '#            1st Column: IOC Type (SIOC, HIOC, VIOC)'
                elif '2nd Column: for hard iocs this is the terminal server' in line:
                    currentIOCInfo['header'] = '#            2nd Column: IOC Name/Alias'
                elif '#            3rd Column: for hard ioc, this is the terminal servier port number' in line:
                    currentIOCInfo['header'] = '#            3rd Column: host user account used to run screen and host where screen is run'
                elif '4th Column: host where' in line:
                    currentIOCInfo['header'] = '#            4th Column: For HIOCs, host user account used to run screen, terminal server, and terminal server port number'
                elif '#                        emulator screen is used by iocConsole.py' in line:
                    currentIOCInfo['header'] = '#                        For SIOCs and VIOCs, full executable path (optional)'
                elif '#            5th Column: description, this column is not used by iocConsole.py' in line:
                    currentIOCInfo['header'] = '#            5th Column: description (optional)'
                elif line in bad_lines:
                    pass
                else:
                    currentIOCInfo['header'] = line
            elif not trimmed_line:
                currentIOCInfo['placeholder'] = ' '
            else:
                columns = line.split(None, 4)
                # For SIOCs, column 3 is "sioc"
                if columns[2] == 'sioc':
                    currentIOCInfo['name'] = columns[0]
                    currentIOCInfo['type'] = 'SIOC'
                    currentIOCInfo['executable'] = columns[1]
                    currentIOCInfo['screenhost'] = columns[3]
                    if len(columns) > 4:
                        currentIOCInfo['description'] = columns[4]

                elif number.match(columns[2]):
                    # For HIOCs, column 3 is a port number
                    currentIOCInfo['name'] = columns[0]
                    currentIOCInfo['type'] = 'HIOC'
                    currentIOCInfo['terminalserver'] = columns[1]
                    currentIOCInfo['port'] = columns[2]
                    currentIOCInfo['screenhost'] = columns[3]
                    if len(columns) > 4:
                        currentIOCInfo['description'] = columns[4]

                elif name.match(columns[2]):
                    # For VIOCs, column 3 is a generic name
                    currentIOCInfo['name'] = columns[0]
                    currentIOCInfo['type'] = 'VIOC'
                    currentIOCInfo['terminalserver'] = columns[1]
                    currentIOCInfo['user'] = columns[2]

                    # Optionally, a path to the executable can be in column 4
                    if len(columns) > 3:
                        if path.match(columns[3]):
                            currentIOCInfo['executable'] = columns[3]
                            if len(columns) > 4:
                                currentIOCInfo['description'] = columns[4]

                        else:
                            currentIOCInfo['description'] = ' '.join(columns[3:])

            # Create header, name, type, user@host, path, comment, and empty_line formatted lists (headers, empty lines, and columns 1, 2, 3, 4, 5)
            if 'header' in currentIOCInfo:
                header_list.append(currentIOCInfo['header'])
            else:
                header_list.append('')

            if "placeholder" in currentIOCInfo:
                empty_lines.append(' ')
            else:
                empty_lines.append('')

            if "name" in currentIOCInfo:
                alias_list.append(currentIOCInfo['name'])
            else:
                alias_list.append('')

            if "type" in currentIOCInfo:
                IOCtype_list.append(currentIOCInfo['type'])
            else:
                IOCtype_list.append('')

            if "screenhost" in currentIOCInfo:
                iocUser = os.environ.get('IOC_OWNER', 'laci')
                user_list.append(iocUser + '@' + currentIOCInfo['screenhost'])
            elif 'user' in currentIOCInfo:
                user_list.append(currentIOCInfo['user'] + '@' + currentIOCInfo['terminalserver'])
            else:
                user_list.append('')

            if "executable" in currentIOCInfo:
                path_list.append(currentIOCInfo["executable"])
            elif "terminalserver" and "port" in currentIOCInfo:
                path_list.append('root@' + currentIOCInfo["terminalserver"] + ':' + currentIOCInfo["port"])
            else:
                path_list.append('')

            if "description" in currentIOCInfo:
                comment_list.append(currentIOCInfo["description"])
            else:
                comment_list.append('')

            #add formatted lists into one, final, formatted list
            formatted_data = [x for x in zip(header_list, IOCtype_list, alias_list, user_list, path_list, comment_list, empty_lines)]

    final_formatted_data = [x for x in formatted_data if x != ('', '', '', '', '', '', '')]

    return final_formatted_data

def updateScreenIOCs(screenIOCsFileName, updatedScreenIOCsFileName):
    final_formatted_data = processScreenIOCs(screenIOCsFileName)

    # print formatted data to new file
    with open(updatedScreenIOCsFileName, 'w') as f2:
        # insert version string
        versionString = '{}{}\n'.format(globals.formatIndicator, globals.format)
        f2.write(versionString)

        # print remaining data
        for sublist in final_formatted_data:
            width = [
                str(sublist[0]),
                str(sublist[1].ljust(8)),
                str(sublist[2].ljust(18)),
                str(sublist[3].ljust(22)),
                str(sublist[4]),
                '  ' + str(sublist[5]),
                str(sublist[6])
            ]
            line = ' '.join(width)
            newline = line.strip()
            f2.write(f'{newline}\n')

if __name__ == '__main__':
    screenIOCsFileName, updatedScreenIOCsFileName = commandoptions()
    updateScreenIOCs(screenIOCsFileName, updatedScreenIOCsFileName)
