#!/usr/bin/env /usr/bin/python3

import cgi, os
import cgitb
import subprocess

cgitb.enable()

cgi.maxlen=10 * 1024

form = cgi.FieldStorage()

fn1=""
fn2=""
fn3=""
fn4=""
fn4a=""
fn5=""

message1=""
message2=""
message3=""
message4=""
message4a=""
message5=""

fileitem = form['filename1']
if fileitem.filename:
  fn1 = os.path.basename(fileitem.filename)
  if fn1.endswith('.txt') :
    open('files/' + fn1, 'wb').write(fileitem.file.read())
    message1 = 'The file "' + fn1 + '" was uploaded successfully'
  else:
    message1 = 'Need to be a txt file'
    fn1 = ""
else:
  message1 = 'No file was uploaded'

fileitem = form['filename2']
if fileitem.filename:
   fn2 = os.path.basename(fileitem.filename)
   if fn2.endswith('.txt') :
      open('files/' + fn2, 'wb').write(fileitem.file.read())
      message2 = 'The file "' + fn2 + '" was uploaded successfully'
   else:
      message2 = 'Need to be a txt file'
      fn2 = ""
else:
   message2 = 'No file was uploaded'

fileitem = form['filename3']
if fileitem.filename:
   fn3 = os.path.basename(fileitem.filename)
   if fn3.endswith('.txt') :
       open('files/' + fn3, 'wb').write(fileitem.file.read())
       message3 = 'The file "' + fn3 + '" was uploaded successfully'
   else:
       message3 = 'Need to be a txt file'
       fn3 = ""
else:
   message3 = 'No file was uploaded'

fileitem = form['filename4']
if fileitem.filename:
   fn4 = os.path.basename(fileitem.filename)
   if fn4.endswith('') or fn4.endswith('.txt') :
       open('files/' + fn4, 'wb').write(fileitem.file.read())
       message4 = 'The file "' + fn4 + '" was uploaded successfully'
   else:
       message4 = 'Need to be empty extension file'
       fn4 = ""
else:
   message4 = 'No file was uploaded'

fileitem = form['filename4a']
if fileitem.filename:
   fn4a = os.path.basename(fileitem.filename)
   if fn4a.endswith('.in') :
       open('files/' + fn4a, 'wb').write(fileitem.file.read())
       message4a = 'The file "' + fn4a + '" was uploaded successfully'
   else:
       message4a = 'Need to be *.in file'
       fn4a = ""
else:
   message4a = 'No file was uploaded'

fileitem = form['filename5']
if fileitem.filename:
   fn5 = os.path.basename(fileitem.filename)
   if fn5.endswith('.txt') :
       open('files/' + fn5, 'wb').write(fileitem.file.read())
       message5 = 'The file "' + fn5 + '" was uploaded successfully'
   else:
       message5 = 'Need to be a txt file'
       fn5 = ""
else:
   message5 = 'No file was uploaded'

##change to files directory
os.chdir(r"files")

## remove files ?

pngName=""
result=""
haha=""
dwba_1=""
dwba_2=""
dwba_3=""
dwba_4=""
dwbaPNG=""
inFile=""
outFile=""
isDWBA=False
dwbaExFile=""
dwbaRootFile=""
isTransferOK=False

#------- if only DWBA
if fn4!="" or fn4a!="":
  if fn4!="":
    dwba_1 = subprocess.run(["../Cleopatra/InFileCreator", fn4, "0", "180", "0.1"] , stdout=subprocess.PIPE).stdout.decode('utf-8')
    cmd = "../Cleopatra/ptolemy <%s.in> %s.out" % (fn4, fn4)

  if fn4a!="":
    fn4 = fn4a.split('.')[0]
    cmd = "../Cleopatra/ptolemy <%s> %s.out" % (fn4a, fn4)

  outFile = fn4+ ".out"
  os.system(cmd)
  isPtolemy = True
  if os.path.exists(outFile) :
    dwba_3 = subprocess.run(["../Cleopatra/ExtractXSec", outFile, "1"], stdout=subprocess.PIPE).stdout.decode('utf-8')
    dwbaRootFile = fn4 + ".root"
    dwbaExFile = fn4 + ".Ex.txt"
    dwba_4 = subprocess.run(["../Cleopatra/PlotTGraphTObjArray", dwbaRootFile, "1"], stdout=subprocess.PIPE).stdout.decode('utf-8')
    dwbaPNG = dwba_4.splitlines().pop()
    isDWBA = True

if fn1=="" or fn2=="":
  result = "imcomplete input files for Kinematics Simulation"
  pngName = ""
  haha = ""
else:
  if isDWBA :
    result = subprocess.run(["../Cleopatra/Transfer", fn1, fn2, dwbaExFile, dwbaRootFile, "transfer.root", "reaction.dat", "0"], stdout=subprocess.PIPE).stdout.decode('utf-8')    
    isTransferOK = True
  else:
    if fn3=="" :
      result = "missing Ex.txt"
    else:
      result = subprocess.run(["../Cleopatra/Transfer", fn1, fn2, fn3, "", "transfer.root", "reaction.dat", "0"], stdout=subprocess.PIPE).stdout.decode('utf-8')
      isTransferOK = True

  if isTransferOK :
    if fn5 =="":
      haha = subprocess.run(["../Cleopatra/PlotSimulation", "transfer.root"],  stdout=subprocess.PIPE).stdout.decode('utf-8')
    else:
      haha = subprocess.run(["../Cleopatra/PlotSimulation", "transfer.root", fn5],  stdout=subprocess.PIPE).stdout.decode('utf-8')
    pngName=haha.splitlines().pop() 


print ("Content-Type: text/html\r\n\r\n")
print ("<html>")
print ("<style> img {max-width: 100%} </style>")
print ("<style> body { font-family: courier, courier new, serif;} </style>")
#print ("<style> a { color: #F7CF3C;} </style>")
print ("<style> a { color: #1363A7;} </style>")
print ("<body>")

if dwbaPNG != "" :
  print ("<img src=\"files/%s\">" % dwbaPNG)
  print ("<br> Downlaod the <a href=\"files/%s\" download=\"%s\">%s</a>" % (fn4+".in", fn4+".in", fn4+".in"))
  print ("<br> Downlaod the <a href=\"files/%s\" download=\"%s\">%s</a>" % (fn4+".out", fn4+".out", fn4+".out"))
  print ("<br> Downlaod the <a href=\"files/%s\" download=\"%s\">%s</a>" % (fn4+".Xsec.txt", fn4+".Xsec.txt", fn4+".Xec.txt"))
  print ("<br> Downlaod the <a href=\"files/%s\" download=\"%s\">%s</a>" % (fn4+".root", fn4+".root", fn4+".root"))

if pngName != "" :
  print ("<img src=\"files/%s\">" % pngName)
  print ("<br> Downlaod the simulation <a href=\"files/transfer.root\" download=\"transfer.root\">root file</a>")

print ("<br><br><br>#################################### programs text output")
print ("<table>")
print ("<tr><td style=\"text-align:right\">Reaction File :</td><td>%s<td></tr>" % message1)
print ("<tr><td style=\"text-align:right\">DetectorGeo File :</td><td>%s<td></tr>" % message2)
print ("<tr><td style=\"text-align:right\">Ex File :</td><td>%s<td></tr>" % message3)
print ("<tr><td style=\"text-align:right\">DWBA File :</td><td>%s<td></tr>" % message4)
print ("<tr><td style=\"text-align:right\">DEBA.in File :</td><td>%s<td></tr>" % message4a)
print ("<tr><td style=\"text-align:right\">Plot Config File :</td><td>%s<td></tr>" % message5)
print ("</table>")
print ("<br><span style=\"white-space: pre-line\"> %s </span>" % dwba_1)
print ("<br><span style=\"white-space: pre-line\"> %s </span>" % dwba_3)
print ("<br><span style=\"white-space: pre-line\"> %s </span>" % dwba_4)
print ("<br><span style=\"white-space: pre-line\"> %s </span>" % result)
print ("<br><span style=\"white-space: pre-line\"> %s </span>" % haha)
print ("</body>")
print ("</html>")
