// cell search <query>
// Searches for packages matching <query>, or actors or modules within them.

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

if (length(args) < 1) {
  log.console("Usage: cell search <query>")
  log.console("Searches for packages, actors, or modules matching the query.")
  $stop()
}

var query = args[0]
var found_packages = []
var found_modules = []
var found_actors = []

// Search through all installed packages
var packages = shop.list_packages()

arrfor(packages, function(package_name) {
  // Check if package name matches
  if (search(package_name, query) != null) {
    push(found_packages, package_name)
  }

  // Search modules and actors within the package
  var _search = function() {
    var modules = pkg.list_modules(package_name)
    arrfor(modules, function(mod) {
      if (search(mod, query) != null) {
        push(found_modules, package_name + ':' + mod)
      }
    })

    var actors = pkg.list_programs(package_name)
    arrfor(actors, function(actor) {
      if (search(actor, query) != null) {
        push(found_actors, package_name + ':' + actor)
      }
    })
  } disruption {
    // Skip packages that can't be read
  }
  _search()
})

// Print results
var total = length(found_packages) + length(found_modules) + length(found_actors)

if (total == 0) {
  log.console("No results found for '" + query + "'")
} else {
  log.console("Found " + text(total) + " result(s) for '" + query + "':")
  log.console("")

  if (length(found_packages) > 0) {
    log.console("Packages:")
    arrfor(found_packages, function(p) {
      log.console("  " + p)
    })
    log.console("")
  }

  if (length(found_modules) > 0) {
    log.console("Modules:")
    arrfor(found_modules, function(m) {
      log.console("  " + m)
    })
    log.console("")
  }

  if (length(found_actors) > 0) {
    log.console("Actors:")
    arrfor(found_actors, function(a) {
      log.console("  " + a)
    })
  }
}

$stop()
