#!/usr/bin/env python

import sys
import shutil
import os
import subprocess

from os.path import dirname, abspath, join, exists
import argparse
import re

parser = argparse.ArgumentParser(description='Generate a KGLT Game Project')
parser.add_argument("output_directory", type=unicode, nargs=1)

PROJECT_NAME_REGEX = "[a-zA-Z0-9_]+"
PROJECT_TITLE_REGEX = ".{1,200}"
PROJECT_PACKAGE_REGEX = "[a-z0-9\.]+"

TEMPLATE_PROJECT_PATH = join(dirname(abspath(__file__)), "template")

def automagicify(project_name, project_package, project_title, output_directory):
    output_dest = join(output_directory, project_name)
    if exists(output_dest):
        confirm = raw_input("Output directory {} already exists, overwrite? [y/N]: ".format(output_dest))
        if confirm != "y":
            print("Project creation cancelled")
            return
        else:
            shutil.rmtree(output_dest)

    shutil.copytree(TEMPLATE_PROJECT_PATH, output_dest)

    # Create a symlink to the game code for android
    android_symlink_src = join(output_dest, project_name)
    android_symlink_dst = join(output_dest, "android", "jni", project_name)

    if not exists(android_symlink_dst):
        os.symlink(android_symlink_src, android_symlink_dst)

    FILES_THAT_NEED_SEARCH_REPLACING = [
        join(output_dest, "manage.py"),
        join(output_dest, "android", "jni", "Android.mk"),
        join(output_dest, "android", "jni", "Application.mk"),
        join(output_dest, "PROJECT_NAME", "main.cpp"),
        join(output_dest, "CMakeLists.txt")
    ]

    for f in FILES_THAT_NEED_SEARCH_REPLACING:
        with open(f, "r") as fin:
            data = fin.read()

        data = data.replace("{PROJECT_NAME}", project_name)
        data = data.replace("{PROJECT_OUTPUT_DEST}", output_dest)
        data = data.replace("{PROJECT_NAME_TITLE}", project_name.title())

        with open(f, "w") as fout:
            fout.write(data)

    to_rename = []

    for dirn, subdirs, files in os.walk(output_dest, topdown=False):
        for directory in subdirs:
            if directory == "PROJECT_NAME":
                src = join(dirn, directory)
                dst = join(dirn, project_name)
                to_rename.append((src, dst))

    for src, dst in to_rename:
        shutil.move(src, dst)

    print("Downloading and updating KGLT for Android")
    subprocess.check_call(["python", "manage.py", "update", "android"], cwd=output_dest)

def main():
    args = parser.parse_args()

    while True:
        project_name = raw_input("Please specify a project name, this should only contain the characters [a-zA-Z0-9_]: ")

        if not re.match(PROJECT_NAME_REGEX, project_name):
            print("Project name was invalid")
            continue
        else:
            break

    while True:
        project_title = raw_input("Please enter the title of the project: ")
        if not re.match(PROJECT_TITLE_REGEX, project_title):
            print("Project title was invalid")
            continue
        else:
            break

    while True:
        project_package = raw_input("Please enter the Android/Java package name (e.g. com.example.game): ")
        if not re.match(PROJECT_PACKAGE_REGEX, project_package) or project_package.count(".") < 2:
            print("Project package was invalid")
            continue
        else:
            break

    automagicify(project_name, project_package, project_title, args.output_directory[0])

    return 0

if __name__ == '__main__':
    sys.exit(main())
