+_ = require "underscore"
+
 Spread = require "./Spread"
 
 # TODO: This should have tests for isEqualTo and contains
 
 module.exports = class SpreadEnv
-  constructor: (@parent, @origin, @index) ->
+  constructor: (@parent, @origin, @index, @length) ->
 
   lookup: (spread) ->
     if spread.origin == @origin

  # Note: assign is not a mutation, it returns a new SpreadEnv where spread is
  # assigned to index.
  assign: (spread, index) ->
    return new SpreadEnv(this, spread.origin, index)

  isEqualTo: (spreadEnv) ->
    return false unless spreadEnv?

    return true if @isEqualTo(spreadEnv)
    return @contains(spreadEnv.parent)

  # Returns a spread of booleans reporting "are you at the location marked by
  # this SpreadEnv?"
  toBooleanSpread: () ->
    # Note: This often returns an irregular ("ragged") spread. These work fine.

    if not @length then return true

    items = _.range(@length).map(() => false)
    items[@index] = @parent.toBooleanSpread()

    new Spread(items, @origin)


SpreadEnv.empty = new SpreadEnv()
