from . import target_base
from . import utils
from . import dirs
from . import db
from . import col
import os.path
join = os.path.join

pypkgname = __name__.split('.')[0]
assert pypkgname != '__main__'

def _ensure_create_pyinit(pkg,compinit):
    d  = dirs.pkg_cache_dir(pkg,'pyinit')
    fn = join(d,('__init__ci.py' if compinit else '__init__.py'))
    if not os.path.exists(fn):
        cont = '#autogenerated file\n"""python module for package %s"""\n'%pkg.name
        if compinit:
            cont+='from . _init import *\n'
        utils.mkdir_p(d)
        open(fn,'w').write(cont)
    return fn

class TargetPyInit(target_base.Target):
    def __init__(self,pkg):
        compinit = os.path.isdir(dirs.pkg_dir(pkg,'pycpp__init'))
        fn=_ensure_create_pyinit(pkg,compinit)
        db.db['pkg2parts'][pkg.name].add('autopyinit__%s'%os.path.basename(fn))
        neededlinks=set([(dirs.installdir / 'python' / pkg.name,'__init__.py',fn)])
        pklfile=dirs.pkg_cache_dir(pkg,'pyinit','pyinit.pkl')
        mpf=dirs.makefile_blddir(pklfile)
        utils.update_pkl_if_changed(neededlinks,pklfile)

        self.name='%s_pyinit'%pkg.name
        self.pkgname=pkg.name
        self.deps=[mpf]
        self.code = ['@if [ ${VERBOSE} -ge 0 ]; then echo "%s  Generating %s/__init__.py%s"; fi'%(col.bldcol('pymod'),pkg.name,col.bldend),
                     'python3 -m%s.instsl2 %s ${VERBOSE}'%(pypkgname,mpf)]

_python_patterns = set(['pycp', 'pyth'])#todo: to conf
def tfactory_pyinit(pkg,dirtypes):
    #if we have pure or compiled python modules and we do not have a
    #user written __init__.py, we will have to add one. That one will
    #either be empty, or include the compiled pycpp__init module.
    if dirtypes.isdisjoint(_python_patterns):
        return []
    if 'pyth' in dirtypes and os.path.exists(dirs.pkg_dir(pkg,'python','__init__.py')):
        return []#user supplied
    return [TargetPyInit(pkg)]




#cleanup: only needed when a package itself is touched, i.e. can take place in target init or in target factories.
#
#issues: remove symlinked scripts, python, data, ...
#        remove library which is no longer created
#        remove app which is no longer created
#
#        can we add a cleanup target? Which is only triggered once after pkg targets are recreated.
