import cctbx.array_family.flex

import boost.python
ext = boost.python.import_ext("phaser_ext")
from phaser_ext import *
import libtbx.load_env
import os.path
import re

class PhaserException(Exception):
    """
    Exception raised in the phaser module
    """
    

class PhaserValueError(PhaserException):
    """
    An object's value is not suitable
    """
    
from phaser import pickle_support
pickle_support.enable()

"""
class _(boost.python.injector, mr_rtest):

  def __getinitargs__(self):
    return (self.MODLID, self.EULER, self.SCORE)

class _(boost.python.injector, mr_dtest):

  def __getinitargs__(self):
    return (self.DEGEN, self.U, self.V)

class _(boost.python.injector, mr_solution):

  def __getinitargs__(self):
    return (self.KNOWN, self.ANNOTATION, self.RLIST, self.DLIST)
"""

def process_default_phil_settings () :
  phaser_path = libtbx.env.dist_path("phaser")
  defaults_file = os.path.join(phaser_path, "defaults")
  assert os.path.isfile(defaults_file)
  print "phaser: Generating libtbx.phil defaults files"
  includes_dir = libtbx.env.under_build("include")
  if (not os.path.exists(includes_dir)) :
    os.mkdir(includes_dir)
  defaults_phil_file = libtbx.env.under_build("include/phaser_defaults.params")
  nma_defaults_phil_file = libtbx.env.under_build("include/phaser_nma_defaults.phil")
  f2 = open(defaults_phil_file, "w")
  f3 = open(nma_defaults_phil_file, "w")
  f2.write("# THIS FILE IS GENERATED AUTOMATICALLY BY SCONS\n")
  f2.write("# DO NOT EDIT!\n")
  f3.write("# THIS FILE IS GENERATED AUTOMATICALLY BY SCONS\n")
  f3.write("# DO NOT EDIT!\n")
  for line in open(defaults_file).readlines() :
    if line.startswith("#") :
      continue
    fields = line.split()
    if len(fields) < 3 :
      raise RuntimeError("""\
Improper formatting of default settings:
%s
""" % line)
    def_name = fields[0]
    phil_name = fields[1]
    value = " ".join(fields[2:])
    if (phil_name != ".") :
      value = re.sub("false", "False", re.sub("true", "True", value))
      if (phil_name.startswith("nma") or phil_name.startswith("sced") or
          phil_name.startswith("ddm") or phil_name.startswith("perturb") or
          phil_name.startswith("enm")) :
        f3.write("keywords.%s = %s\n" % (phil_name, value))
      else :
        f2.write("phaser.keywords.%s = %s\n" % (phil_name, value))
  f2.close()
  f3.close()
