#!/usr/bin/env python
import sys
import html

class Entry(object):
    def __init__(self):
        self.items = {
            'title': '',
            'authors': '',
            'conference': '',
            'link': '',
            'website': '',
            'regstatus': ''
        }

def esc(x):
    # Strip surrounding quotes in the source file and escape HTML
    return html.escape(x.strip().strip('"'))

outf = open('../data/pubs.html', 'w')
# outf = open('./pubs.html', 'w')

def print_entry(d):
    title      = esc(d['title'])
    authors    = esc(d['authors'])
    conf       = esc(d['conference'])
    link       = d['link'].strip().strip('"')
    website    = d['website'].strip().strip('"')

    # default to 'y' if regstatus missing or empty
    regstatus  = d.get('regstatus', '').strip().lower()
    if regstatus == '':
        regstatus = 'y'

    outf.write('<div class="col-md-8">\n')

    # Title with bookmark
    outf.write(
        f'<p><font color="#003458"><i class="fa-solid fa-bookmark"></i> {title}</font><br>\n'
    )

    # Authors
    outf.write(f'<font color="grey"><i>{authors}</i></font><br>\n')

    # Conference + DOI link with scroll
    outf.write(
        f'{conf} <a href="{link}" target="_blank" rel="noopener noreferrer" '
        f'style="background-color: white; color: #003458;"><i class="fa-solid fa-scroll"></i></a>'
    )

    # 🔴 Show check only if regstatus == 'n'
    if regstatus == 'n':
        outf.write(' <i class="fa-solid fa-check" style="color:grey;" title="Not registered"></i>')

    outf.write('\n')

    # Optional project website with cloud
    if website:
        outf.write(
            f' <a href="{website}" target="_blank" rel="noopener noreferrer" '
            f'style="background-color: white; color: #003458;"><i class="fa-solid fa-cloud"></i></a>'
        )

    outf.write('</p>\n')
    outf.write('</div>\n')

counter = 0
comments = 0
for line in open('../data/publications.txt'):
    line_stripped = line.strip()
    etype = line_stripped.split(' ')[0].split(':')[0] if line_stripped else ''

    if not line or not line_stripped:
        # blank line -> end of an entry (unless at start or after comments)
        if counter == 0 or comments == 1:
            comments = 0
            continue
        outf.write(f'<!-- p{counter} -->\n')
        print_entry(edat.items)
        continue

    if line[0] == '#':
        comments = 1
        continue

    if etype == 'title':
        counter += 1
        edat = Entry()
        edat.items[etype] = line.split(f'{etype}:', 1)[1].strip()
        continue

    # other fields
    if etype in edat.items:
        edat.items[etype] = line.split(f'{etype}:', 1)[1].strip()

# If the file does not end with a blank line, you could optionally flush the last entry:
# if counter > 0 and edat.items.get('title'):
#     outf.write(f'<!-- p{counter} -->\n')
#     print_entry(edat.items)
