// cell add <locator> [alias] - Add a dependency to the current package
//
// Usage:
//   cell add <locator>         Add a dependency using default alias
//   cell add <locator> <alias> Add a dependency with custom alias
//   cell add -r <directory>    Recursively find and add all packages in directory
//
// This adds the dependency to cell.toml and installs it to the shop.

var shop = use('internal/shop')
var pkg = use('package')
var fd = use('fd')

var locator = null
var alias = null
var recursive = false
var cwd = fd.realpath('.')
var parts = null
var locators = null
var added = 0
var failed = 0
var _add_dep = null
var _install = null
var i = 0

var run = function() {
  for (i = 0; i < length(args); i++) {
    if (args[i] == '--help' || args[i] == '-h') {
      log.console("Usage: cell add <locator> [alias]")
      log.console("")
      log.console("Add a dependency to the current package.")
      log.console("")
      log.console("Examples:")
      log.console("  cell add gitea.pockle.world/john/prosperon")
      log.console("  cell add gitea.pockle.world/john/cell-image image")
      log.console("  cell add ../local-package")
      log.console("  cell add -r ../packages")
      return
    } else if (args[i] == '-r') {
      recursive = true
    } else if (!starts_with(args[i], '-')) {
      if (!locator) {
        locator = args[i]
      } else if (!alias) {
        alias = args[i]
      }
    }
  }

  if (!locator && !recursive) {
    log.console("Usage: cell add <locator> [alias]")
    return
  }

  if (locator)
    locator = shop.resolve_locator(locator)

  // Generate default alias from locator
  if (!alias && locator) {
    parts = array(locator, '/')
    alias = parts[length(parts) - 1]
    if (search(alias, '@') != null)
      alias = array(alias, '@')[0]
  }

  // Check we're in a package directory
  if (!fd.is_file(cwd + '/cell.toml')) {
    log.error("Not in a package directory (no cell.toml found)")
    return
  }

  // Recursive mode
  if (recursive) {
    if (!locator) locator = '.'
    locator = shop.resolve_locator(locator)
    if (!fd.is_dir(locator)) {
      log.error(`${locator} is not a directory`)
      return
    }
    locators = filter(pkg.find_packages(locator), function(p) {
      return p != cwd
    })
    if (length(locators) == 0) {
      log.console("No packages found in " + locator)
      return
    }
    log.console(`Found ${text(length(locators))} package(s) in ${locator}`)

    added = 0
    failed = 0
    arrfor(locators, function(loc) {
      var loc_parts = array(loc, '/')
      var loc_alias = loc_parts[length(loc_parts) - 1]
      log.console("  Adding " + loc + " as '" + loc_alias + "'...")
      var _add = function() {
        pkg.add_dependency(null, loc, loc_alias)
        shop.sync(loc)
        added = added + 1
      } disruption {
        log.console(`  Warning: Failed to add ${loc}`)
        failed = failed + 1
      }
      _add()
    })

    log.console("Added " + text(added) + " package(s)." + (failed > 0 ? " Failed: " + text(failed) + "." : ""))
    return
  }

  // Single package add
  log.console("Adding " + locator + " as '" + alias + "'...")

  _add_dep = function() {
    pkg.add_dependency(null, locator, alias)
    log.console("  Added to cell.toml")
  } disruption {
    log.error("Failed to update cell.toml")
    return
  }
  _add_dep()

  _install = function() {
    shop.sync_with_deps(locator)
    log.console("  Installed to shop")
  } disruption {
    log.error("Failed to install")
    return
  }
  _install()

  log.console("Added " + alias + " (" + locator + ")")
}
run()

$stop()
