#!/usr/bin/env python3
import json
import string
import random
import glob, os
import sys

def close_sdk(path, sdk):
    # print("processing content: %s..." % path)
    with open(path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    with open(path, "w", encoding="utf-8") as f_w:
        is_sdk_code = False
        for line in lines:
            if "//SDK-"+sdk+"-END" in line or "<!--SDK-"+sdk+"-END-->" in line:
                is_sdk_code = False

            java_mark ="//SDK-" + sdk + "-CODE ->";
            xml_mark ="<!--SDK-" + sdk + "-CODE//";
            if (path.endswith(".java") or path.endswith(".gradle")) and is_sdk_code and java_mark not in line:
                line = java_mark + line

            if path.endswith(".xml") and is_sdk_code and xml_mark not in line:
                line = xml_mark + line.replace("\n","//-->\n")

            if "//SDK-"+sdk+"-START" in line or "<!--SDK-"+sdk+"-START-->" in line:
                is_sdk_code = True

            f_w.write(line)
    return

def open_sdk(path, sdk):
    # print("processing content: %s..." % path)
    code_mark = "//SDK-" + sdk + "-CODE ->"
    xml_mark = "<!--SDK-" + sdk + "-CODE//"
    with open(path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    with open(path, "w", encoding="utf-8") as f_w:
        for line in lines:
            if code_mark in line:
                line = line.replace(code_mark,"")
            if xml_mark in line:
                line = line.replace(xml_mark,"").replace("//-->","")
            f_w.write(line)
    return


print ("params "+sys.argv[1] + " "+sys.argv[2])

lib_base_gradle = "../build.gradle"
if sys.argv[1] == 'open':
    open_sdk(lib_base_gradle, sys.argv[2])
else:
    close_sdk(lib_base_gradle, sys.argv[2])

app_build_gradle = "../../app/build.gradle"
if sys.argv[1] == 'open':
    open_sdk(app_build_gradle, sys.argv[2])
else:
    close_sdk(app_build_gradle, sys.argv[2])

for root, dirs, files in os.walk("../../app/src/main"):
    directory = os.path.join(os.getcwd(), root)
    for file in files:
        if file.endswith(".java") or file.endswith("AndroidManifest.xml") or file.endswith(".gradle"):
            # get the path of the java file
            path = os.path.join(directory, file)
            if sys.argv[1] == 'open':
                open_sdk(path, sys.argv[2])
            else:
                close_sdk(path, sys.argv[2])


for root, dirs, files in os.walk("../../lib_base/src/main"):
    directory = os.path.join(os.getcwd(), root)
    for file in files:
        if file.endswith(".java") or file.endswith("AndroidManifest.xml") or file.endswith(".gradle"):
            # get the path of the java file
            path = os.path.join(directory, file)
            if sys.argv[1] == 'open':
                open_sdk(path, sys.argv[2])
            else:
                close_sdk(path, sys.argv[2])