import flask
from flask import Flask, request
import requests
from PIL import ImageFile, Image
import os
import shutil
import subprocess

ImageFile.SAFEBLOCK = 2048*2048

app = Flask(__name__)
app.base_project = "/apps/3ps/build_apk/PalioBrowserGen"
app.base_project_name = os.path.basename(app.base_project)
app.temp_folder = "/apps/3ps/build_apk/BuildApk"
app.verbose = True

def vprint(*data):
    if app.verbose:
        print(*data)

def create_folder(package_id):
    path = os.path.join(app.temp_folder, package_id)
    if not os.path.exists(path):
        os.mkdir(path)
    else:
        shutil.rmtree(path)
        os.mkdir(path)
    vprint(path)
    path_dest = os.path.join(path,app.base_project_name)
    if not os.path.exists(path_dest):
        shutil.copytree(app.base_project, path_dest)
    code_path = "app/src/main/java/"
    orig_code = "io/palio/browser"
    path_package_id = package_id.replace(".","/")
    c_code_path = os.path.join(path_dest, code_path, path_package_id)
    orig_code_path = os.path.join(path_dest, code_path, orig_code)
    if not os.path.exists(c_code_path):
        shutil.copytree(orig_code_path,c_code_path)
        shutil.rmtree(orig_code_path)
    return path_dest, c_code_path

def change_url(c_code_path, url):
    main_activity = os.path.join(c_code_path, "MainActivity.java")
    with open(main_activity, "r") as f:
        file_source = f.read()
    replaced = file_source.replace("https://www.google.com",url)
    with open(main_activity, "w") as f:
        f.write(replaced)

def change_name(path_dest, name):
    manifest = os.path.join(path_dest, "app/src/main/AndroidManifest.xml")
    with open(manifest, "r") as f:
        file_source = f.read()
    replaced = file_source.replace("Palio Brow", name)
    with open(manifest, "w") as f:
        f.write(replaced)

def change_package(path_dest, package):
    build_gradle = os.path.join(path_dest, 'app/build.gradle')
    with open(build_gradle, "r") as f:
        file_source = f.read()
    replaced = file_source.replace("io.palio.browser", package)
    with open(build_gradle, "w") as f:
        f.write(replaced)
    manifest = os.path.join(path_dest, "app/src/main/AndroidManifest.xml")
    with open(manifest, "r") as f:
        file_source = f.read()
    replaced = file_source.replace("io.palio.browser", package)
    with open(manifest, "w") as f:
        f.write(replaced)
    path_package_id = package.replace(".", "/")
    code_path = "app/src/main/java/"
    code_path = os.path.join(path_dest,code_path,path_package_id)
    javas = [os.path.join(dp, f) for dp, dn, filenames in os.walk(code_path) for f in filenames]
    for j in javas:
        with open(j, "r") as f:
            file_source = f.read()
        replaced = file_source.replace("io.palio.browser", package)
        with open(j, "w") as f:
            f.write(replaced)

def change_logo(path_dest, logo):
    img_path = "app/src/main/res/drawable/pb_palio_ball.png"
    img_path = os.path.join(path_dest, img_path)
    if isinstance(logo,str):
        logo = requests.get('https://qmera.io/dashboardv2/uploads/logo/{}'.format(logo))
        with open(img_path, "wb") as f:
            f.write(logo.content)
        with open(img_path, "rb") as f:
            logo = Image.open(f)
            logo = logo.resize((150, 150))
        logo.save(img_path, "PNG")
    else:
        logo = Image.open(logo)
        logo = logo.resize((150,150))
    logo.save(img_path,"PNG")

def run_build(path_dest):
    gradlew = os.path.join(path_dest,"gradlew")
    ret = subprocess.run([gradlew, 'assembleRelease'])
    return ret.returncode

def deliver_apk(path_dest):
    apk_dir = os.path.join(path_dest,'app/build/outputs/apk/release')
    vprint(apk_dir)
    try:
        return flask.send_from_directory(apk_dir,'app-release.apk')
    except Exception as e:
        return str(e)

@app.route('/', methods=["GET","POST"])
def build_apk():
    if request.method == 'POST':
        logo = None
        app_name = None
        package_id = None
        home_url = None
		
        if 'logo' in request.files:
            logo = request.files['logo']
            vprint(type(logo))
        elif 'logo' in request.form:
            logo = request.form['logo']
            vprint(type(logo))
			
        if 'app_name' in request.files:
            app_name = request.files['app_name']
            vprint(app_name)
        elif 'app_name' in request.form:
            app_name = request.form['app_name']
            vprint(app_name)
			
        if 'package_id' in request.files:
            package_id = request.files['package_id']
            vprint(package_id)
        elif 'package_id' in request.form:
            package_id = request.form['package_id']
            vprint(package_id)
			
        if 'url' in request.files:
            home_url = request.files['url']
            vprint(home_url)
        elif 'url' in request.form:
            home_url = request.form['url']
            vprint(home_url)
			
        if package_id is None:
            package_id = 'com.app.qmera'
			
        path_dest, c_code_path = create_folder(package_id)
        vprint("path_dest: " + path_dest)
        vprint("c_code_path: "+c_code_path)
        change_url(c_code_path, home_url)
        change_name(path_dest, app_name)
        change_package(path_dest,package_id)
        if logo:
            change_logo(path_dest,logo)
        os.chdir(path_dest)
        return_code = run_build(path_dest)
        if(return_code == 0):
            return deliver_apk(path_dest)
        return "h"
    else:
        if 'e' in request.args:
            return request.args['e']
        return "Hello World!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8090, debug=app.verbose, ssl_context=('/etc/ssl/STAR_qmera_io/qmera_io.crt', '/etc/ssl/STAR_qmera_io/qmera.key'))
