#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import re
import random
import subprocess
import cgi
import platform

import genswf

def runBuilder( wm3dbuilder, finput ):
  cmdline = [wm3dbuilder]
  p = subprocess.Popen( cmdline,
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE )
  fh = open( finput, "r" )
  line = fh.readline()
  while line:
    p.stdin.write( line )
    line = fh.readline()
  fh.close()
  return( p.communicate()[0] )

if __name__ == "__main__":
  workdir = "/tmp/"
  wm3dbuilder = "/home/kamo/haXe/wm3d/scripts/python/builder/builder.py"

  form = cgi.FieldStorage()
  # save pdb data to file, temporary
  [ fh, pdbfile ] = genswf.getNewFile( workdir, "wmxml", ".pdb" )
  pdbdata = str( form.getvalue( "h_pdbdata" ) )
  if platform.system() == "Windows":
    # ad hoc work around
    pdbdata = re.sub( r'ATOM   ', '\nATOM   ', pdbdata )
    pdbdata = re.sub( r'HETATM ', '\nHETATM ', pdbdata )
  fh.write( pdbdata )
  fh.close()
  # create input file for builder
  builderinput = re.sub( r'\.pdb$', '.input', pdbfile )
  fin = open( builderinput, "w" )
  fin.write( "l " + pdbfile + "\n" )
  # write atom parameters, if exists
  if form.has_key( "h_atomdata" ):
    fin.write( str( form.getvalue( "h_atomdata" ) ) )
  # write secondary structure params, if exists
  if form.has_key( "h_secdata" ):
    fin.write( str( form.getvalue( "h_secdata" ) ) )
  # add query fields
  fin.write( str( form.getvalue( "h_query" ) ) )
  fin.write( "wmxml\n" )
  fin.write( "q\n" )
  fin.close()

  data = runBuilder( wm3dbuilder, builderinput )

  # remove files
  if os.path.isfile( pdbfile ):
    os.remove( pdbfile )
  if os.path.isfile( builderinput ):
    os.remove( builderinput )

  print "Content-Type: text/plain"
  print
  print data
