#!/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:
            mark ="//SDK-" + sdk + "-CODE ->";
            if is_sdk_code and mark not in line:
                line = mark + line

            if "//SDK-"+sdk+"-START" in line :
                is_sdk_code = True

            if "//SDK-"+sdk+"-END" in line :
                is_sdk_code = False

            f_w.write(line)
    return

def open_sdk(path, sdk):
    # print("processing content: %s..." % path)
    code_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:
        is_sdk_code = False
        for line in lines:
            if code_mark in line:
                line = line.replace(code_mark,"")

            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(".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(".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])