metadata:
  title: Bulk Package Install
  sessions are unique: True
  required privileges:
    - admin
    - developer
  temporary session: True
---
modules:
  - .aldashboard
---
objects:
  - packages: DAList.using(object_type=DAObject, there_are_any=True, complete_attribute="github_url")
---
mandatory: True
id: interview order
code: |
  packages.gather()
  if install_packages_task.ready():
    ending_screen
  else:
    waiting_screen
---
question: |
  What packages do you want to install?
list collect: True
fields:
  - Github URL: packages[i].github_url
  - YAML filename: packages[i].yaml_name
  - Short name or alias (no spaces): packages[i].alias
    validate: |
      lambda y: y.isidentifier()
---
code: |
  install_packages_task = background_action('install_packages_event')
---
event: install_packages_event
code: |
  background_error_action("bg_failure")
  for package in packages:
    pkgname = install_from_github_url(package.github_url)
    reset(pkgname)

  the_config = da_get_config()
  if not the_config.get("dispatch"):
    the_config["dispatch"] = {}
  for package in packages:
      package_regex = r"https:\/\/github\.com\/.*\/docassemble-([\w]*)"
      match = re.search(package_regex, package.github_url)
      if match:
        package_path = f"docassemble.{ match.groups()[0] }:data/questions/{ package.yaml_name }"
        the_config["dispatch"][package.alias] = package_path
  results = da_write_config(the_config)

  background_response_action("bg_success")
---
event: bg_success
code: |
  it_worked = True
  background_response()
---  
event: waiting_screen
question: |
  Wait here while we start the installation process
reload: True
---
event: bg_failure
code: |
  it_worked = False
  background_response()
---
event: ending_screen
question: |
  All done
subquestion: |
  % if it_worked:
  It may take a few minutes for the installation process to complete.

  You can now use these links to reach your interviews:
  
  % for package in packages:
  * [${package.alias}](/start/${package.alias})
  % endfor
  % else:
  Something went wrong. Check the [worker.log](/logs?file=worker.log) to learn what.
  % endif
buttons:
  - Restart: restart