def align_R(s, width):
    return (' '*width + str(s))[-width:]

def align_L(s, width):
    return (str(s)+' '*width)[:width]

def table(texts, order, width, align):
    dash_line = ('+' + '-'*width)*3 + '+\n'
    t = dash_line
    header = True
    for line in texts:
        x = [e.strip() for e in line.split(',')]
        t += '|' + align(x[order[0]], width) + \
             '|' + align(x[order[1]], width) + \
             '|' + align(x[order[2]], width) + '|\n'
        if header:
            t += dash_line
            header = False
    t += dash_line
    return t.strip()

with open('part_c2_template.txt', encoding='utf-8') as f:
    template = f.read()

texts = '''ID, Mid (30),Final (100)
P49203, 25, 45
P44949,  5,   100
P50392x, 29,48
P52812a1,27,   8'''.splitlines()

orders = [[0,2,1], [1,0,2], [1,2,0], [2,0,1], [2,1,0]]
widths = [11, 12, 13]
aligns = [align_R, align_L]

out = '<P>\n'
for order in orders:
    for width in widths:
        for align in aligns:
            t = template
            t = t.replace('$$WIDTH$$', str(width))
            if align == align_L:
                t = t.replace('$$ALIGN$$', 'ซ้าย')
            else:
                t = t.replace('$$ALIGN$$', 'ขวา')
            t = t.replace('$$TABLE$$', table(texts, order, width, align))
            out += t
out += '</P>'
            
with open('part_c2.txt', 'w', encoding='utf-8') as f:
    f.write(out)


