#!/usr/bin/python -u

import getopt
import json
import os
import shutil
import sys
import time
from urllib.request import urlopen
from urllib.request import urlretrieve

from subprocess import call


import commands as cmd

PROD_DEPLOYMENTS_URL = "https://adservernet.enplug.com/v1/edu/app/deployments"
STAGING_DEPLOYMENTS_URL = "https://staging-adserver.enplug.com/v1/edu/app/deployments"
KONE_STAGING_URL = "https://s3-us-west-2.amazonaws.com/enplug-android-image/test/StagingPlayer.apk"

def main(argv):
    print('[1] Reboot')
    print('[2] Clear Device Cache')
    print('[3] Set Custom Zoning Host Version')
    print('[4] Use Zoning Host URL Set via Dashboard')
    print('[5] Staging <-> Production')
    print('[6] Logs')
    print('')
    # print ('[B] Build .exe File')
    print ('[Q] Quit')
    sys.stdout.flush()

    option = input().strip().lower()

    if option == "1":
        reboot()
    elif option == "2":
        clearCache()
    elif option == "3":
        setZoningVersion()
    elif option == "4":
        deleteCustomZoningHost()
    elif option == "5":
        changeEnvironment()
    elif option == "6":
        showLogOptions()
    elif option == "b":
        build()

    elif option == "q":
        sys.exit(0)

    sys.stdout.flush()


def build():
    run_command(cmd.build_binary)
    shutil.rmtree('build')
    os.remove('commands.pyc')
    os.remove('enplug_device.spec')


def changeEnvironment():
    log("Select target environment", True)
    log('[1] Staging')
    log('[2] Production')
    log('[3] KONE Staging')
    option = input().strip().lower()
    is_kone = False

    if option == "1":
        log("Changing device environment to: STAGING", True)
        url = STAGING_DEPLOYMENTS_URL
    elif option == "2":
        log("Changing device environment to: PRODUCTION")
        url = PROD_DEPLOYMENTS_URL
    elif option == "3":
        log("Changing KONE device environment to STAGING", True)
        is_kone = True
    else:
        log("Invalid input. Exiting.")
        sys.exit()

    if is_kone:
        downloadFile(KONE_STAGING_URL, "Player.apk")
        run_command(cmd.uninstall_package)
        run_command(cmd.install_package)
        log("Please wait (20s) while the script makes appropriate database changes...", True)
        time.sleep(20)
        run_command(cmd.set_staging_flag_in_db)
        run_command(cmd.reboot)
        return

    log("Fetching deployment URLs from " + url)

    response = urlopen(url)
    html = response.read()
    package_json_data = json.loads(html)
    player_packages = package_json_data["Result"]

    for pkg in player_packages:
        if pkg["AppName"] == "Player":
            downloadFile(pkg["PackageUrl"], "Player.apk")
            run_command(cmd.uninstall_package)
            run_command(cmd.install_package)
            if (option == "1"):     # Staging
                log("Please wait (20s) while the script makes appropriate database changes...", True)
                time.sleep(20)
                run_command(cmd.set_staging_flag_in_db)
            run_command(cmd.reboot)


def clearCache():
    log("Clearing cache...")
    sys.stdout.flush()
    run_command(cmd.clear_cache)


def deleteCustomZoningHost():
    run_command(cmd.delete_custom_zoning_host_url)
    run_command(cmd.reboot)


def downloadFile(url, filename):
    log("Downloading package file: " + url)
    urlretrieve(url, filename)
    log("Downloaded file and saved as " + filename)

def deleteAllLogFiles():
    run_command(cmd.delete_all_logs)

def log(message, new_line=False):
    if new_line:
        print()
    print(message)
    sys.stdout.flush()


def reboot():
    log("Rebooting device...")
    sys.stdout.flush()
    run_command(cmd.reboot)


def run_command(command, *params):
    command = command.format(*params)
    log("Executing command: ", True)
    log('  ' + command)
    command = command.split()
    call(command)


def setZoningVersion():
    log("Enter new version: ")
    ver = input().strip()
    run_command(cmd.set_version, ver)
    run_command(cmd.reboot)

def showLogOptions():
    log('[1] Download Logs Directory')
    log('[2] Download Logs as One File')
    log('[3] Delete All Logs')
    option = input().strip().lower()

    if option == "1":
        log("Downloading logs directory...", True)
    elif option == "2":
        log("Downloading and concatenating available logs...")
    elif option == "3":
        log("Deleting all logs...")
        deleteAllLogFiles()
    else:
        log("Invalid input. Exiting.")
        sys.exit()


if __name__ == "__main__":
    main(sys.argv[1:])
