class_name Cutscene

const CUTSCENE_CONTINUE = -1
const CUTSCENE_END = -2

const CUTSCENE_ADD_END = -1
const CUTSCENE_ADD_NEXT = -2

var running:bool = false
var index:int = 0
var queue:Array[Dictionary] = []

# Accepts;
#   function:Callable - The function to add
#   position:int - Where to add the function (default: end)
#   data:Dictionary - Data to pass to the function when called
func addCallable(params:Dictionary) -> int:
  assert(params.has("function"))

  if !params.has("position"):
    params["position"] = CUTSCENE_ADD_END
  
  params['cutscene'] = self
  
  if params["position"] == CUTSCENE_ADD_END || params["position"] >= queue.size():
    queue.append(params)
    return queue.size() - 1

  elif params["position"] == CUTSCENE_ADD_NEXT:
    queue.insert(index + 1, params)
    return index + 1

  queue.insert(params["position"], params)
  return params["position"]


func addCallables(params:Dictionary) -> Array[int]:
  assert(params.has("functions"))
  var indexes:Array[int] = []
  for element in params['functions']:
    var newDict = element.merged(params, false)
    newDict.erase('functions')
    indexes.append(addCallable(newDict))
  return indexes

func start() -> void:
  if queue.size() == 0:
    return

  assert(!running)
  running = true
  index = 0
  while index < queue.size():
    var queueItem = queue[index]
    var result = await queueItem['function'].call(queueItem)

    match result:
      CUTSCENE_CONTINUE:
        index += 1

      CUTSCENE_END:
        break
      
      _:
        index = result

    if index < 0:
      break

  running = false
