#!/usr/bin/env python

from path import path
from jinja2 import Template
import sys

SKIP_DIRS = ["native"]
NON_AUTOLOAD_MODULES = ["ads", "analytics"]
MONKEY = Template("""Strict

Public

{% for filename in filenames -%}
Import {{ module }}.{{ filename }}
{% endfor %}""")


def walkdir(dirpath, proc_func, rec_func):
    def is_valid_dir(dirpath):
        if dirpath.islink():
            return False
        if dirpath.name.startswith(".") or dirpath.name in SKIP_DIRS:
            return False
        return True

    [rec_func(dirpath / x.name) for x in dirpath.dirs() if is_valid_dir(x)]
    proc_func(dirpath)


def create_import_files(dirname):
    def process(dirpath):
        filenames = [x.stripext().name for x in dirpath.files()]
        rendered = MONKEY.render(filenames=filenames, module=dirpath.name)
        (dirpath + ".monkey").write_text(rendered)

    walkdir(path(dirname), process, create_import_files)


def add_reflection_rule():
    def replace_public(instr):
        return instr.replace(
            "Public",
            "Public\n\n#REFLECTION_FILTER+=\"*test|*src.tests*\"")

    filepath = path("src/tests.monkey")
    filepath.write_text(replace_public(filepath.text()))


def remove_non_autoload_modules():
    def is_autoload(importstr):
        for checkstr in NON_AUTOLOAD_MODULES:
            if checkstr in importstr:
                return False
        return True

    filepath = path("src.monkey")
    filepath.write_lines([x for x in filepath.lines() if is_autoload(x)])


def create_symlinks(dirname):
    def process(dirpath):
        levels = len(dirpath.splitall()) - 1
        des = dirpath / "bono"
        if des.exists():
            des.remove()
        path("../" * levels).symlink(dirpath / "bono")

    walkdir(path(dirname), process, create_symlinks)


if __name__ == "__main__":
    create_import_files("src")
    create_import_files("tests")
    create_symlinks("src")
    add_reflection_rule()
    remove_non_autoload_modules()

    path("src.monkey").rename("bono.monkey")
    path("tests.monkey").rename("testimport.monkey")
    path("src/bono").remove()

@@ -143,17 +143,227 @@
 alytics%22
-%5D
+, %22payment%22%5D%0ANON_AUTOLOAD_FILES = %7B%0A    %22payment%22: %5B%0A        %22paymentproviderandroidgoogle%22,%0A        %22paymentproviderandroidamazon%22,%0A        %22paymentproviderappleios%22,%0A        %22paymentproviderautounlock%22%0A    %5D%0A%7D
 %0AMONKEY 
@@ -850,32 +850,184 @@
 files(dirname):%0A
+    def is_valid(module, filename):%0A        try:%0A            return filename not in NON_AUTOLOAD_FILES%5Bmodule%5D%0A        except:%0A            return True%0A%0A
     def process(
@@ -1101,16 +1101,88 @@
 iles()%5D%0A
+        filenames = %5Bx for x in filenames if is_valid(dirpath.name, x)%5D%0A
         

handle payment case in tools/create-module-imports.py