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

################################################
import pandas as pd

# the API webpage
# https://www-nds.iaea.org/relnsd/vcharthtml/api_v0_guide.html#examples

# the service URL
livechart = "https://nds.iaea.org/relnsd/v0/data?"

import urllib.request

def lc_read_csv(url):
  req = urllib.request.Request(url)
  req.add_header('User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0')
  return pd.read_csv(urllib.request.urlopen(req))

mp = 938.27208816 #MeV/c^2
mn = 939.56542052

#===================================================
import cgi, cgitb

form = cgi.FieldStorage()

AZ = form.getvalue('isotopes_name')
maxEx = form.getvalue('maxEx')

if maxEx == "can be omitted" :
  maxEx = -1

query = livechart + "fields=ground_states&nuclides=" + AZ
temp = lc_read_csv(query)

print( "Content-type:text/html\r\n\r\n")
print("<html>")
print("<style> body { font-family: courier, courier new, serif; color: #F7CF3C; } </style>")
print("<body>")

print("<br>========================= " + AZ )
try :
  Z = temp['z'][0]
  N = temp['n'][0]
  mass = Z*mp + N*mn - (Z+N)*temp['binding']/1000
  halfLife = temp['half_life_sec'][0]

  print("<br>    A : %3d, Z : %3d, N : %3d" % (Z+N, Z, N))
  print("<br>  Jpi : %3s" % (temp['jp'][0]))
  #if halfLife != " " :
  print("<br> half-live : %s sec" % (halfLife))
  print("<br> Mass : %.4f MeV" % (mass))
  print("<br> Binding : %.4f MeV/A" % (temp['binding']/1000))
  print("<br> Binding : %.4f MeV" % (temp['binding']/1000*(Z+N)))

  #print("   magnetic dipole : " + temp['magnetic_dipole'][0] + " mu.N")
  #print("electric quadruple : " + temp['electric_quadrupole'][0] + " barn")
  #if halfLife > 0 :
  #  print('------------ decay mode:')
  #  for i in range(1, 4) :
  #    print("%5s  %s %%" % (temp["decay_%d" % i][0], temp["decay_%d_%%" % i][0]))
  #  print('--------------------------')
except :
  print("<br>No such Isotopes.")


import os, subprocess
os.chdir(r"files")

result=subprocess.run(['../Cleopatra/IsotopeShort', AZ],  stdout=subprocess.PIPE).stdout.decode('utf-8')
p1 = result.find('Sn:')
print("<br>" + result[p1:p1+16])
p1 = result.find('Sp')
print("<br>" + result[p1:p1+16])
p1 = result.find('Sa')
print("<br>" + result[p1:p1+16])
print("<br>=============================")

if float(maxEx) > 0 :
  print("<br>")
  query = livechart + "fields=levels&nuclides=" + AZ
  tempEx = lc_read_csv(query);
  ex = tempEx['energy']
  jp = tempEx['jp']
  l = ex.last_valid_index()
  try :
      print("<table>")
      for i in range(0, l+1):
        if float(ex[i]) < float(maxEx)*1000:
          print("<tr><td style=\"text-align:right\" width=80> %9.3f </td><td style=\"text-align:right\" width=100> %s </td></tr>" % (ex[i], jp[i].replace(' ', ',')))
        else:
          break
      print("</table>")
  except:
    print("<br> cannot find Ex data")


print("</body>")
print("</html>")




