#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Web example script to get HTML author URL from author in list
# Copyright (C) 2014-2025 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com
#

import csv
import sys
import re;


if len(sys.argv) != 4:
   sys.stderr.write('Usage: get-author-url author_list author_name default_text\n')
   sys.exit(1)

replaceBbspStrings = re.compile('&nbsp;', re.UNICODE)

authorList = sys.argv[1]
authorName = replaceBbspStrings.sub(' ', sys.argv[2])
authorText = sys.argv[3]


csv.register_dialect('authors', delimiter=' ', quoting=csv.QUOTE_MINIMAL,skipinitialspace=True)

inputFile = open(authorList, 'r')
inputCSV = csv.reader(inputFile, dialect='authors')

authorRow = None
for row in inputCSV:
   # print row
   if row[0] == authorName:
      if authorRow != None:
         # the authorName is multiple times in the table -> warning
         sys.stderr.write('WARNING: Multiple occurrences of authorName ' + authorName + ' in ' + authorList + '!\n')
      authorRow = row


if authorRow == None:
   # The authorName is not in the table -> use default text
   sys.stdout.write(authorText)
   sys.stderr.write('Not in list: ' + authorName + '\n')
   sys.exit(0)
else:
   # Found the authorName -> print the result
   sys.stdout.write('<a href="' + authorRow[1] + '">' + authorText + '</a>')
