module CCG::TriggerListHelper
  class InnerBuilder
    def with_key(key)
      @key = key
      self
    end

    def with_title(title)
      @title = title
      self
    end

    def with_action(action)
      @action = action
      self
    end

    def build
      raise CCG::LogicError, 'Trigger is missing key' if @key.nil?

      raise CCG::LogicError, "Trigger #{key} is missing title" if @title.nil?

      raise CCG::LogicError, "Trigger #{key} is missing action" if @action.nil?

      CCG::GameModel::Trigger.new(@key, @title, @action)
    end
  end

  def trigger
    @trigger_builders ||= []
    new_builder = InnerBuilder.new
    @trigger_builders.push(new_builder)
    new_builder
  end

  def try_compute_triggers
    if @trigger_list.nil?
      @trigger_builders ||= []

      @trigger_list = @trigger_builders.map(&:build)
      @triggers = Hash[
        @trigger_list.map { |trigger| [trigger.key, trigger] }
      ].with_indifferent_access

      @trigger_builders = nil
    end
  end

  def trigger_list
    try_compute_triggers

    @trigger_list
  end

  def triggers
    try_compute_triggers

    @triggers
  end
end
