from os.path import join, islink, samefile, isdir, exists
from os import listdir, symlink, makedirs
from qpy.compile import compile_qpy_files
import dulcinea

def build_ui_mirror(package, path_in_package):
    assert path_in_package.startswith('/uiqp')
    package_path = package.__path__[0]
    relative_uiqp = path_in_package
    relative_ui = '/ui' + relative_uiqp[5:]
    for name in listdir(package_path + relative_ui):
        if name.endswith('~'):
            continue
        if name.endswith('.pyc'):
            continue
        if name.endswith('.pyo'):
            continue
        if name.startswith('.'):
            continue
        if path_in_package == '/uiqp' and name.startswith('__init__.py'):
            continue
        src = join(package_path + relative_ui, name)
        if name.endswith('.ptl'):
            dst = join(package_path + relative_uiqp, name[:-4] + '.qpy')
        else:
            dst = join(package_path + relative_uiqp, name)
        if islink(dst):
            assert samefile(dst, src), (src, dst)
        elif isdir(src):
            if not exists(dst):
                makedirs(dst)
        else:
            try:
                symlink(src, dst)
            except OSError:
                print (src, dst)
                raise
    compile_qpy_files(package_path + relative_uiqp)

build_ui_mirror(dulcinea, '/uiqp')
build_ui_mirror(dulcinea, '/uiqp/lib')
build_ui_mirror(dulcinea, '/uiqp/user')
build_ui_mirror(dulcinea, '/uiqp/form2')
build_ui_mirror(dulcinea, '/uiqp/test')

