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

import os
import sys
import math
import re

from system import *

class SystemMgr:
  def __init__( self ):
    self.clear()

  def clear( self ):
    self.addwmxml = False
    self.datatype = ""
    self.systems = []
    self.query = PdbQuery()
    self.storedata = ""

  def clearAtoms( self ):
    System.clearAtoms()

  def showAtoms( self ):
    System.showAtoms()

  def registerAtom( self, args ):
    System.registerAtom( args )

  def initQuery( self ):
    self.query.clear()

  def addMolQuery( self, query ):
    self.query.selectMolecules( query )

  def addResQuery( self, query ):
    self.query.selectResidues( query )

  def addAtomQuery( self, query ):
    self.query.selectAtoms( query )

  def select( self ):
    for eachsys in self.systems:
      eachsys.select( self.query )
    self.initQuery()

  def purgeData( self, toWhat = sys.__stdout__ ):
    if not self.hasData():
      return
    if self.addwmxml:
      print >> toWhat, "<WMXML>"
    print >> toWhat, System.globalSetting(),
    if len( self.storedata ) > 0:
      self.systems[0].storedata = self.storedata
    for eachsys in self.systems:
      eachsys.purgeData( toWhat )
    if self.addwmxml:
      print >> toWhat, "</WMXML>"

  def storeData( self ):
    if not self.hasData():
      return
    for eachsys in self.systems:
      tmpval = ""
      if eachsys.hasData():
        tmpval = eachsys.storeData()
        self.storedata = "".join( [ self.storedata, tmpval ] )
    self.systems = []

  def hasData( self ):
    for eachsys in self.systems:
      if eachsys.scenedata != "":
        return( True )
    return( False )

  def totatom( self ):
    num = 0
    for eachsys in self.systems:
      num += eachsys.totatom()
    return( num )

  def natom( self ):
    num = 0
    for eachsys in self.systems:
      num += eachsys.natom()
    return( num )

  def genAtoms( self, arg = None ):
    num = 0
    for eachsys in self.systems:
      num += eachsys.genAtoms( arg )
    return( num )

  def genBonds( self, arg = None ):
    num = 0
    for eachsys in self.systems:
      num += eachsys.genBonds( arg )
    return( num )

  def genChains( self, gencoil = False ):
    num = 0
    for eachsys in self.systems:
      num += eachsys.genChains( gencoil )
    return( num )

  def write( self, toWhat ):
    for eachsys in self.systems:
      eachsys.write( toWhat )
      print >> toWhat, "END   "

  def readPDB( self, fromWhat ):
    self.datatype = "PDB"
    self.storeData()
    text = ""
    for line in fromWhat:
      text += "\n" + line
    splittedpdb = text.split( "END" )
    for eachpdb in splittedpdb:
      eachsys = System()
      eachsys.readPDB( eachpdb.splitlines() )
      self.systems.append( eachsys )
