#
#
#


__author__ = "Randall J. Radmer"
__version__ = "1.0"
__doc__ = """This is a simple class wrapper for the VMD NAMD interface code. """

DEFAULT_PORT=54321

import threading, time

import vmdimd_raw as imd_raw

class Vmdimd(object):
    def __init__(self, port=None):
        super(Vmdimd, self).__init__()
        if port:
            self.port=port
        else:
            self.port=DEFAULT_PORT
        Vmdimd.VmdimdSetup(self.port)

    class VmdimdSetup(threading.Thread):
        def __init__(self, port):
            threading.Thread.__init__(self)
            self.port=port
            self.start()
 
        def run(self):
            imd_raw.makeConnection(self.port)

        def closeConnection(self):
            imd_raw.closeConnection()


    def stopTryingConnection(self):
        imd_raw.stopTryingConnection()

    def closeConnection(self):
        imd_raw.closeConnection()

    def sendCoords(self, coords):
        imd_raw.sendCoords(coords)

    def sendEnergies(self,
                     tstep=0,
                     T=300.0,
                     Etot=0.0,
                     Epot=0.0,
                     Evdw=0.0,
                     Eelec=0.0,
                     Ebond=0.0,
                     Eangle=0.0,
                     Edihe=0.0,
                     Eimpr=0.0):
        imd_raw.sendEnergies(tstep,
                             T,
                             Etot,
                             Epot,
                             Evdw,
                             Eelec,
                             Ebond,
                             Eangle,
                             Edihe,
                             Eimpr)


def parseCommandLine():
    opts, args_proper = getopt.getopt(sys.argv[1:], 'h')
    for option, parameter in opts:
        if option=='-h': usageError()
    return (args_proper)


def main():
    import math
    args_proper = parseCommandLine()
    sys.stdout.write("Make Connection!\n")
    sys.stdout.flush()
    v=Vmdimd()
    sys.stdout.write("Made Connection!\n")
    sys.stdout.flush()
    maxCount=3600
    sys.stdout.write("Start!\n")
    sys.stdout.flush()
    try:
        for i in range(maxCount):
            sys.stdout.write("%d\n" % i)
            sys.stdout.flush()
            scale=2*(1-i/float(maxCount))
            x=scale*math.cos(math.pi*i/180.0)
            y=scale*math.sin(math.pi*i/180.0)
            z=0.0
            coords=[ (x,y,z) ]
            v.sendEnergies(tstep=i, Etot=i/10.0)
            v.sendCoords(coords)
            time.sleep(0.01)
    except KeyboardInterrupt:
        pass
    v.closeConnection()
    sys.stdout.write("Done!\n")
    sys.stdout.flush()

def usageError():
    usageString= 'usage: python %s' % os.path.basename(sys.argv[0])
    sys.exit(1)

if __name__=='__main__':
    import os, sys, getopt
    main()

