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


# def gen_rand_str():
#     rand_str = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=8))
#     return rand_str + str(random.randint(0, 1000000))


def setAdress(line):
    if "${email}" in line:
        if len(sys.argv[2]) > 0:
            line = line.replace("${email}", sys.argv[2])
    if "${phone_num}" in line:
        if len(sys.argv[3]) > 0:
            line = line.replace("${phone_num}", sys.argv[3])
    if "${adress}" in line:
        if len(sys.argv[4]) > 0:
            line = line.replace("${adress}", sys.argv[4])
    return line


def create_desc(read_path, write_path):
    with open(read_path, "r") as f:
        lines = f.readlines()

    index = random.randint(0, 12) + 1

    if int(sys.argv[8]) > 0:
        index = sys.argv[8]

    search_str = "@Example " + str(index) + "-"
    is_target = False
    print (search_str)
    print (sys.argv[1])

    with open(write_path, "w") as f_w:
        for line in lines:

            if search_str in line:
                is_target = True
                continue

            if is_target and "@End" in line:
                is_target = False
                continue

            if is_target:
                line = line.replace("${app_name}", sys.argv[1])
                line = setAdress(line)
                if len(line) > 0:
                    f_w.write(line)


def create_config(read_path, write_path):
    with open(read_path, "r") as f:
        lines = f.readlines()

    with open(write_path, "w") as f_w:
        for line in lines:
            line = line.replace("${app_name}", sys.argv[1]) \
                .replace("${desc}", sys.argv[5] + "_desc.txt") \
                .replace("${privacy_url}", sys.argv[6] + "?name=" + sys.argv[1].replace(" ", "%20")) \
                .replace("${website}", "")
            # .replace("${website}",sys.argv[7])
            f_w.write(line)


output = "/Users/connor/Documents/apks/" + sys.argv[5] + "_" + sys.argv[1]
if not os.path.exists(output):
    os.makedirs(output)

create_desc("/Users/connor/StudioProjects/WorkSpace/app_desc.txt",
            output + "/" + sys.argv[5] + "_desc.txt")

# create_config("/Users/connor/StudioProjects/WorkSpace/config.json", output + "/config.json")
