from pathlib import Path


def schema_convert(base_dir):
    base_dir = Path(base_dir).absolute()
    schema_file = base_dir / 'schema.ini'
    with open(schema_file, 'r', encoding='latin-1') as frh:
        schema = frh.read()
    # schema = schema.replace('\n\n', '\n').replace('\n\n', '\n')
    tables = dict([convert_table_info(t) for t in schema[1:].split('\n[')])

    for table, details in tables.items():
        table_file = base_dir / table
        if 'schema.ini' in table or not table_file.exists():
            continue
        format_file = base_dir / (table + '.xml')

        record = []
        row = []
        for i, c in details['columns'].items():
            col_name = c.split(' ')[0]
            record.append(f'  <FIELD ID="{i}" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="255" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>')
            row.append(f'  <COLUMN SOURCE="{i}" NAME="{col_name}" xsi:type="SQLVARYCHAR"/>')
        record[-1] = record[-1].replace(';', '\\r\\n')

        with open(format_file, 'w') as fwh:
            fwh.write('<?xml version="1.0"?>\n<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" ')
            fwh.write('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n<RECORD>\n')
            fwh.write('\n'.join(record))
            fwh.write('\n</RECORD>\n<ROW>\n')
            fwh.write('\n'.join(row))
            fwh.write('\n</ROW>\n</BCPFORMAT>')
    # print(tables)


def convert_table_info(table_info):
    info = table_info.split(']\n')
    if len(info) < 2:
        return ('', '')
    details = {}
    details['columns'] = {}
    for key, value in ([row.split('=') for row in info[1].split('\n') if '=' in row]):
        if key.lower() != 'colnameheader' and key.lower()[:3] == 'col':
            details['columns'][key[3:]] = value
    return (info[0], details)


if __name__ == '__main__':
    schema_convert('C:\\GlobalCube_LOCOSOFT\\GCStruct_SKR51\\Kontenrahmen')
    # plac.Interpreter.call(IqdConverter)
