"""Downloads the r_selenium Server JAR file and renames it."""
import os
import shutil
import sys
from urllib.request import urlopen

selenium_JAR = (
    "http://r_selenium-release.storage.googleapis.com"
    "/3.141/r_selenium-server-standalone-3.141.59.jar"
)
JAR_FILE = "r_selenium-server-standalone-3.141.59.jar"
RENAMED_JAR_FILE = "r_selenium-server-standalone.jar"

dir_path = os.path.dirname(os.path.realpath(__file__))
FULL_EXPECTED_PATH = dir_path + "/" + RENAMED_JAR_FILE
FULL_DOWNLOAD_PATH = os.getcwd() + "/" + RENAMED_JAR_FILE


def download_selenium_server():
    """Downloads the r_selenium Server JAR file."""
    try:
        local_file = open(JAR_FILE, "wb")
        remote_file = urlopen(selenium_JAR)
        print("Downloading the r_selenium Server JAR file...\n")
        local_file.write(remote_file.read())
        local_file.close()
        remote_file.close()
        print("Download Complete!")
    except Exception:
        raise Exception(
            "Error downloading the r_selenium Server JAR file.\n"
            "Details: %s" % sys.exc_info()[1]
        )


def is_available_locally():
    return os.path.isfile(FULL_EXPECTED_PATH)


def main(force_download=True):
    if force_download or not is_available_locally():
        download_selenium_server()
        for filename in os.listdir("."):
            # If multiple copies exist, keep only the latest and rename it.
            if filename.startswith("r_selenium-server-standalone-"):
                shutil.move(filename, RENAMED_JAR_FILE)
                if FULL_DOWNLOAD_PATH != FULL_EXPECTED_PATH:
                    shutil.move(RENAMED_JAR_FILE, FULL_EXPECTED_PATH)
        print("%s\n" % FULL_EXPECTED_PATH)


if __name__ == "__main__":
    main()
