#!c:\Program Files\Python39\python.exe
# -*- coding: UTF-8 -*-

import os, cgitb, sys

# ***** include the biocase.lib directory in the python sys path for importing *****
exec(open(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'lib', 'biocase', 'adjustpath.py'))).read())

from biocase.configtool.general import dsa, schema, form
cgitb.enable()

import biocase.configuration
cfg = biocase.configuration.Cfg()

if dsa is None:
    # This means we're supposed to view a log file (dsa and schema are set to None)
    log = os.path.join(cfg.logLocator, form.getvalue('filename'))
    print('Content-Type: text/plain; charset=UTF-8\n')
else:
    # else it's about archiving logs
    print('Content-Type: text/html; charset=UTF-8\n\n<pre>')
    if form.getvalue('fromworkfolder') == 'true':
        log = os.path.join(cfg.archiveWorkLocator, dsa, schema) + '.log'
    else:
        log = os.path.join(cfg.archiveDownloadLocator, dsa, schema) + '.log'

# Set encoding to UTF8 and encoding error handling to replace
sys.stdout.reconfigure(encoding='utf8', errors='replace')

try:
    f = open(log, "r", encoding='utf8')
    for line in f.readlines():
        # Do some formatting for archiving logs (DEBUG and ERROR lines)
        if dsa is not None:
            if not (line.startswith('INFO') or line == '\n'):
                line = '<font color="%s">%s</font>' % ('#FF0000' if line.startswith('ERROR') else '#FF6600', line)
        # use sys.stdout in order not to print new line or space
        sys.stdout.write(line)
        # This is a fix for pre Python 3.7 version (e.g. Jacq Vienna)
        # sys.stdout.write(line.encode(sys.stdout.encoding, 'replace').decode(sys.stdout.encoding))
    f.close()
except Exception as err:
    print("ERROR - Log file could not be found:\n%s" % (err))