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

This script demonstrates how to create and deploy a webapp based on a public repository with ngrok or cloudflare
as tunnelling engine.
The script will create a webapp based on a public repository and deploy it to the
target Ratio1 Edge Node.

If an ngrok edge label or a cloudflare token is provided, the webapp will be accessible via a permanent URL.
In case ngrok is used and no edge label is provided, a unique URL will be generated by the ngrok service.
The temporary URL will be retrieved and printed to the console.

Note: In the case of a temporary URL, if the node is restarted, a new URL will be generated.

"""
from os import environ
from ratio1 import Session


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

  node = environ.get("EE_TARGET_NODE", "INSERT_YOUR_NODE_ADDRESS_HERE")

  session.wait_for_node(node)

  # This is optional and if not tunnel engine is provided, the default will be ngrok.
  tunnel_engine = environ.get("TUNNEL_ENGINE", "ngrok").lower()

  # In case of using ngrok this is optional!
  # If an ngrok edge label or a cloudflare token is provided, the webapp will be accessible via a permanent URL.
  # In case this is not provided by the user and ngrok is used, a unique URL will be generated by the ngrok service.
  # Warning! create_webapp method does not support multiple nodes.
  # If you want to deploy the webapp to multiple nodes, you can use the create_and_deploy_balanced_web_app method
  ngrok_edge_label = environ.get("NGROK_EDGE_LABEL", None)
  cloudflare_token = environ.get("CLOUDFLARE_TOKEN", None)

  # Defining the environment variables for the webapp.
  # Here we can pass anything we want to the webapp.
  env_vars = {
    'LOCAL_ADDRESS': '/edge_node/_local_cache/_data/local_info.json',
    "VAR_NAME_1": "value1",
    "VAR_NAME_2": "value2",
  }

  # 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",
    # The below are only necessary for private repos
    "username": "<username>",
    "token": "<git_user_token>",
  }

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

  # instance: PLUGIN_TYPES.CUSTOM_WEBAPI_01
  pipeline, instance = session.create_web_app(
    node=node,
    name="Ratio1_WebApp_tutorial",
    env_vars=env_vars,
    setup_commands=setup_commands,
    run_command=run_command,
    tunnel_engine=tunnel_engine,
    ngrok_edge_label=ngrok_edge_label,
    cloudflare_token=cloudflare_token,
    assets=assets,
  )

  url = pipeline.deploy()

  # print the url of the webapp
  if ngrok_edge_label is None and cloudflare_token is None:
    session.P(
      f"Webapp available at: {url}.\nNote that this url is temporary. "
      f"In case the node is restarted, a new url will be generated.\n"
      f"In case you see an ngrok gateway error please try again after a few seconds.",
      color='g', boxed=True, show=True
    )
  else:
    msg = f"Webapp deployed using {tunnel_engine}. "
    msg += "For the url check the settings of the provided ngrok edge label or cloudflare token."
    session.P(msg, color='g', boxed=True, show=True)
  # endif ngrok_edge_label is None and cloudflare_token is None

  # 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
  )
