"""
ex13_launch_repo_based_webapp.py
-------------------------------

This script demonstrates how to create and deploy a webapp based on a public repository using ngrok
edge definition. The script will create a webapp based on a public repository and deploy it to the 
target Ratio1 Edge Node and assing it the same ngrok edge label. 

TODO:
This will be modified so that it will start a generic webapp and generates a dynamic URL that can 
be used to access the webapp. For this demo, we will use a custom webapp that resides at a 
public repository location.

"""
from os import environ
from ratio1 import Session, PLUGIN_SIGNATURES


if __name__ == "__main__":
  session = Session()

  nodes = [
    environ.get("EE_TARGET_NODE_1", "INSERT_YOUR_NODE_ADDRESS_HERE"),
    environ.get("EE_TARGET_NODE_2", "INSERT_YOUR_NODE_ADDRESS_HERE")
  ]

  if isinstance(nodes, str):
    nodes = [nodes]

  for node in nodes:
    session.wait_for_node(node)

  # In case this is not provided and create_and_deploy_balanced_web_app is used an exception will be raised.
  # In case this is not provided by the user, but create_webapp method is used, a unique URL will be generated by the ngrok service.
  # Warning! create_webapp method does not support multiple nodes.
  ngrok_edge_label = environ.get("NGROK_EDGE_LABEL", None)

  # Defining the environment variables for the webapp.
  port = 3000
  env_vars = {
    'APP_PORT': port,
    'LOCAL_ADDRESS': '/edge_node/_local_cache/_data/local_info.json'
  }

  # Defining the webapp setup commands.
  setup_commands = [
    "npm install"
  ]

  # Defining the assets of the application.
  assets = {
    'operation': "clone",
    "url": "https://github.com/ratio1/demo-deploy-nodejs",
  }

  # Defining the webapp run commands.
  run_command = "npm start"

  # instance: PLUGIN_TYPES.CUSTOM_WEBAPI_01
  session.create_and_deploy_balanced_web_app(
    nodes=nodes,
    name="Ratio1_WebApp_tutorial",
    signature=PLUGIN_SIGNATURES.GENERIC_WEB_APP,
    env_vars=env_vars,
    port=port,
    setup_commands=setup_commands,
    run_command=run_command,
    ngrok_edge_label=ngrok_edge_label,
    assets=assets
  )

  # Observation:
  #   next code is not mandatory - it is used to keep the session open and cleanup the resources
  #   in production, you would not need this code as the script can close after the pipeline will be sent
  session.run(
    wait=True,  # wait for the user to stop the execution
    close_pipelines=True  # when the user stops the execution, the remote edge-node pipelines will be closed
  )
