from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os.path as osp
import os

import waflib
import waflib.Logs as _msg
from waflib import Task
from waflib.TaskGen import extension, feature, before_method, after_method

@extension('.pyx')
def add_cython_file(self, node):
  """
  Process a *.pyx* file given in the list of source files. No additional
  feature is required::

    def build(bld):
      bld(features='c cshlib pyext', source='main.c foo.pyx', target='app')
  """
  ext = '.pyx.c'
  if 'cxx' in self.features:
    self.env.append_unique('CYTHONFLAGS', '--cplus')
    ext = '.cc'
  tsk = self.create_task('cython', node, node.change_ext(ext))
  self.source += tsk.outputs

def build(ctx):
  def injectpath(task):
    import re
    src = task.inputs[0].abspath()
    tgt = task.outputs[0].abspath() 
    f=open(src)
    txt = f.read()
    txt = re.sub("REPLACEPATH",ctx.env.PYTHONDIR,txt)
    txt = re.sub("PYTHONEXE",ctx.env.PYTHON[0],txt)
    f=open(tgt,"w")
    print(txt, end=' ', file=f)
    f.close()
  
  uselib_clik = [ff for ff in ('hdf5 chealpix lapack pmc dl cfitsio extra cc_omp fc_runtime' ).split() if ff]
    
  ctx.load("execconfig","waf_tools")
  if ctx.env.CYTHON:
    ctx(
      features = "c cshlib pyext",
      source = "clik/lkl.pyx",
      target  = "lkl",
      includes = "../"+" ../minipmc/"*(not ctx.env.has_pmc),
      use = "clik",
      uselib = uselib_clik,
      #cflags = "-fopenmp",
      install_path = "${PYTHONDIR}/clik"
    )
    ctx(
      features = "c cshlib pyext",
      source = "clik/lkl_lensing.pyx",
      target  = "lkl_lensing",
      includes = "../"+" ../minipmc/"*(not ctx.env.has_pmc),
      use = "clik",
      uselib = uselib_clik,
      #cflags = "-fopenmp",
      install_path = "${PYTHONDIR}/clik",
      defines = ["CLIK_LENSING"]
    ) 
    if (ctx.env.has_plik):
      ctx.env.append_unique("CYTHONFLAGS","-I"+osp.join(os.getcwd(),"src/python/clik"))
      ctx(
        features = "c cshlib pyext",
        source = "clik/parametric.pyx",
        target  = "parametric",
        includes = "../ ../plik/"+" ../minipmc/"*(not ctx.env.has_pmc),
        use = "clik",
        uselib = uselib_clik,
        #cflags = "-fopenmp",
        install_path = "${PYTHONDIR}/clik"
      )
      for plg in ctx.env.PLG:
        for prc in getattr(ctx.env,"PLG_%s_PYTHON"%plg):
          ctx(
          features = "c cshlib pyext",
          source = osp.join("../plik/component_plugin",plg,prc),
          target  = prc.split(".")[0],
          includes = "clik/ ./ ../  ../plik/"+" ../minipmc/"*(not ctx.env.has_pmc),
          use = "clik",
          uselib = uselib_clik,
          #cflags = "-fopenmp",
          install_path = "${PYTHONDIR}/clik"
        ) 
  # import ipdb; ipdb.set_trace()
  
  ctx(
    source = "clik/parobject.py clik/__init__.py clik/miniparse.py clik/smicahlp.py clik/hpy.py clik/cldf.py",
    install_path = "${PYTHONDIR}/clik",
    install_from = ctx.path.find_node("clik")
  )

  if ctx.env.has_bicep:
    ctx(
      source = "../bicep/bicep_util.py",
      install_path = "${PYTHONDIR}",
      install_from=None
    )
  
  
  # python execs

  tls = os.listdir("src/python/tools")
  execlist = [ex for ex in tls if ".py" in ex]
  for cde in execlist:
    ctx(
      execrule = injectpath,
      source = osp.join("tools",cde),
      target = cde[:-3],
      install_path = ctx.env.BINDIR
      )    

  ##if osp.exists("src/bicep"):
  ##  ctx(
  ##    execrule = injectpath,
  ##    source = "../bicep/bicep_main.py",
  ##    target = "bicep_main",
  ##    install_path = ctx.env.BINDIR
  ##    )    
  if osp.exists("src/mspec"):
    ctx(
      execrule = injectpath,
      source = "../mspec/mspec_main.py",
      target = "mspec_main",
      install_path = ctx.env.BINDIR
      )    
  ##if ctx.env.has_momento:
  ##  ctx(
  ##    execrule = injectpath,
  ##    source = "../momento/momento_main.py",
  ##    target = "momento_main",
  ##    install_path = ctx.env.BINDIR
  ##    )    
  ##  ctx(
  ##    source = "../momento/momento.py",
  ##    install_path = "${PYTHONDIR}",
  ##    target = "momento",
  ##    install_from=ctx.path.find_dir('../momento'),
  ##  )
  ##  ctx(
  ##    features = "c cshlib pyext",
  ##    source = "../momento/momento_fast.pyx ../momento/momento_support.c",
  ##    target  = "momento_fast",
  ##    includes = "../"+" ../minipmc/"*(not ctx.env.has_pmc),
  ##    use = "clik",
  ##    #uselib = uselib_clik,
  ##    #cflags = "-fopenmp",
  ##    install_path = "${PYTHONDIR}"
  ##  )


  ###    if (ctx.env.has_f90 and ctx.env.has_egfs):
  ###      ctx(
  ###        features = "c cshlib pyext",
  ###        source = "clik/egfs.pyx",
  ###        target  = "egfs",
  ###        includes = "../"+" ../minipmc/"*(not ctx.env.has_pmc),
  ###        use = "clik",
  ###        cflags = "-fopenmp",
  ###        install_path = "${PYTHONDIR}/clik"
  ###      )
