from __future__ import print_function
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      oeffner
#
# Created:     04/05/2018
# Copyright:   (c) oeffner 2018
# Licence:     <your licence>
#-------------------------------------------------------------------------------


# This file should live on www-structmed@arctic-1:/var/www/html/htdocs/Local/PhaserNightly
# and be executed whenever a regression test suite has finished by on of the platforms
# It will then update/create a contents.html file with links to regression and build logs
# Execute it from individual regression shell scripts (such as nightlybuildscript.sh )
# like:
# ssh www-structmed@arctic-1 'cd /var/www/html/htdocs/Local/PhaserNightly && python MakeRegressionTestContents.py'
#

import os.path, re, sys, glob, time


def CountErrorsAndOKs(fname):
  # count errors and oks as printed in the regression log file output
  if os.path.exists(fname):
    with open(fname, "r") as mfile:
      mstr = mfile.read()
      python_oks = len(re.findall("(python \s+ - \s+ OK)", mstr, re.DOTALL | re.VERBOSE))
      python_errs = len(re.findall("(python \s+ - \s+ ERROR)", mstr, re.DOTALL | re.VERBOSE))
      keyword_oks = len(re.findall("(script \s+ - \s+ OK)", mstr, re.DOTALL | re.VERBOSE))
      keyword_errs = len(re.findall("(script \s+ - \s+ ERROR)", mstr, re.DOTALL | re.VERBOSE))
      pybgr, kbgr = "", ""
      if (python_oks + python_errs) > 0:
        red = int(255.0 * python_errs/(python_oks + python_errs))
        green = int(255.0 * python_oks/(python_oks + python_errs))
        pybgr = 'style = "background-color:rgb(%d, %d, %d); color:black;text-align:center" ' %(red,green, 0)
      if (keyword_oks + keyword_errs) > 0:
        red = int(255.0 * keyword_errs/(keyword_oks + keyword_errs))
        green = int(255.0 * keyword_oks/(keyword_oks + keyword_errs))
        kbgr = 'style = "background-color:rgb(%d, %d, %d); color:black;text-align:center" ' %(red,green, 0)
      return python_oks, python_errs, keyword_oks, keyword_errs, pybgr, kbgr
  return -1, -1, -1, -1, "", ""


def CountBootstrapOKsFails(fname):
  # count errors and oks as printed in the regression log file output
  if os.path.exists(fname):
    bgr = 'style = "background-color:green;color:black;text-align:center" '
    with open(fname, "r") as mfile:
      mstr = mfile.read()
      oks = len(re.findall("( \s+ \[OK\] \s+ )", mstr, re.DOTALL | re.VERBOSE)) # just count the "[OK]" instances
      failsstr = re.findall( r"""
        Summary\:  \s* \r* \n
        \s* Tests \s* run \s*   \: \s*   \d* \r* \n
        \s* Failures      \s*   \: \s* ( \d+ ) \r* \n
        """, mstr, re.MULTILINE | re.VERBOSE
      )
      fails = 0
      if len(failsstr):
        fails = int(failsstr[0]) # extract the number of fails from the summary section
        red = int(255.0 * fails/(oks + fails))
        green = int(255.0 * oks/(oks + fails))
        bgr = 'style = "background-color:rgb(%d, %d, %d); color:black;text-align:center" ' %(red,green, 0)
      return oks, fails, bgr
  return 0, 0, ""


def ComposeContentsHtmlFile():
  time.sleep(5) # avoid possible race condition if logfiles haven't been properly written to webserver
  # row in table with cells containing platform name, links to log files and status of test results
  # cell with status is a table in itself with two cells, one for python script and one for keyword script
  platformrow= """  <tr>
    <td> %s </td>
    <td> %s </td>
    <td>
      <table>
        <tr><td >%s </td></tr>
        <tr><td %s >%d OK(s), %d FAIL(s)</td></tr>
      </table>
    </td>
    <td> %s </td>
    <td> %s </td>
    <td> %s </td>
    <td>
      <table>
        <tr><td %s >Python script: %d OK(s), %d Error(s)</td></tr>
        <tr><td %s >Keyword script: %d OK(s), %d Error(s)</td></tr>
      </table>
    </td>
  </tr>
  """
  buildlogstrtmpl = '<a href="%s/buildlog.txt">Build log</a>'
  terselogstrtmpl = '<a href="%s/terse_regression.txt">Terse output</a>'
  bstraptestlogstrtmpl = '<a href="%s/run_tests_parallel_zlog.txt">Bootstrap test</a>'
  textlogstrtmpl = '<a href="%s/PhaserRegressionOutPut.txt">Text output</a>'
  htmllogstrtmpl = '<a href="%s/PhaserRegressionOutPut.html">HTML output</a>'

  # preample for html contents file with the beginning of our table
  htmlstr ="""
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <HEAD>

  <META http-equiv=Content-Type content="text/htm; charset=utf-8">

  <style type="text/css">
  <!--
  .noline {text-decoration:none; color:#000000;}
  body {font-family: verdana, helvetica, arial, sans-serif; font-size: 0.9em}
  td {font-family: verdana, helvetica, arial, sans-serif; font-size: 0.9em}
  -->
  </style>

  <title>Phaser Regression Test Results</title>
  </HEAD>

  <body>
  <h1>Latest Phaser regression test results</h1>
  <p>Click on
  <ul>
    <li>Build logs to inspect bootstrap build,</li>
    <li>Terse logs for a quick breakdown of succeeded and failed tests,</li>
    <li>Normal logs for text comparison of results,</li>
    <li>HTML logs for hypertext markup language formatted output of test results</li>
  </ul>
  </p>

  Platform is the joint strings of : &ltOS-kernel&gt_&ltcompiler&gt_&ltpython version&gt_&ltphaser repo&gt
  <br><br>

  <table border = "1">
    <tr>
      <th>Platform</th>
      <th>Build log</th>
      <th>Bootstrap tests</th>
      <th>Terse log long tests</th>
      <th>Normal log long tests</th>
      <th>Html log long tests</th>
      <th>Status long tests</th>
    </tr>
  """

  curregdirs = glob.glob("Current*")
  # Folders with regression results are named "Current_" + OSname. Split it and pair it with the folder names as in:
  #  [('linux-gnu', 'Current_linux-gnu'), ('darwin15', 'Current_darwin15'), ('Windows_10', 'Current_Windows_10')]
  platform_regrdirs = [ (dir.split("Current_")[1], dir ) for dir in curregdirs ]

  errbgr = 'style = "background-color:red;color:white;text-align:center" '
  OKbgr = 'style = "background-color:green;color:black;text-align:center" '

  def TblCellStr(fname, tmplstr):
    celllogstr = tmplstr %regrdir
    regrfname = os.path.join(regrdir, fname)
    if not os.path.isfile(regrfname):
      celllogstr = ""
    else:
      celllogstr += " <br> " + time.ctime(os.path.getmtime(regrfname))
    return celllogstr

  for platform, regrdir in platform_regrdirs:
    pybgr = OKbgr
    kbgr = OKbgr
    bstraptestlogstr = TblCellStr("run_tests_parallel_zlog.txt", bstraptestlogstrtmpl )
    terselogstr = TblCellStr("terse_regression.txt", terselogstrtmpl )
    buildlogstr = TblCellStr("buildlog.txt", buildlogstrtmpl )
    textlogstr = TblCellStr("PhaserRegressionOutPut.txt", textlogstrtmpl )
    htmllogstr = TblCellStr("PhaserRegressionOutPut.html", htmllogstrtmpl )
    # pick one of the regression text log files to count numbers of OKs and ERRORs
    python_oks, python_errs, keyword_oks, keyword_errs, pybgr, kbgr =  \
      CountErrorsAndOKs(os.path.join(regrdir, "terse_regression.txt"))
    """
    if python_errs>0:
      pybgr = errbgr
    if keyword_errs>0:
      kbgr = errbgr
    if python_errs<=0 and python_oks <=0:
      pybgr = ''
    if keyword_errs<=0 and keyword_oks<=0:
      kbgr = ''
    """
    bOks, bFails, bstraptestbgr = CountBootstrapOKsFails(os.path.join(regrdir, "run_tests_parallel_zlog.txt"))
    # 11 variables in a format statement would be messy to read so let's first
    # create a tuple to use in the format statement to platformrow
    formatargs = []
    formatargs.append(platform)
    formatargs.append(buildlogstr)
    formatargs.append(bstraptestlogstr)
    formatargs.append(bstraptestbgr)
    formatargs.append(bOks)
    formatargs.append(bFails)
    formatargs.append(terselogstr)
    formatargs.append(textlogstr)
    formatargs.append(htmllogstr)
    formatargs.append(pybgr)
    formatargs.append(python_oks)
    formatargs.append(python_errs)
    formatargs.append(kbgr)
    formatargs.append(keyword_oks)
    formatargs.append(keyword_errs)
    # format platformrow with these variables and concatenate it to htmlstr
    tablerowstr = platformrow %tuple(formatargs)
    htmlstr = htmlstr + tablerowstr

  htmlstr = htmlstr + """
  </table>

  <p><a href="Past/">Past log files</a>  </p>
  </body>

  """
  open("contents.html","w").write(htmlstr)
  print("done")



if __name__ == '__main__':
  ComposeContentsHtmlFile()
