class Action < ActiveRecord::Base

  serialize :options

  belongs_to :actionable, polymorphic:true

  # === Action Execution ===

  def execute!
    send(command)
  end


  # TODO: Validate that the store is accessible from the current location.
  def set_store
    Game.current.goto_store! Store.lookup(options[:code])
  end

  def start_event
    Game.current.enqueue_event! Event.lookup(options[:code])
  end

  def set_event
    Game.current.set_event! Event.lookup(options[:code])
  end

  def complete_event
    Game.current.complete_event!
  end

  def set_conversation
    Game.current.set_conversation! Conversation.lookup(options[:code])
  end

  def complete_conversation
    Game.current.complete_conversation!
  end

  # === Action Seed ===

  # Seeds should be moved into a different class, a seeder maybe?

  def self.manufacture_each actionable, data
    if data.present?
      data.each do |action_data|
        Action.manufacture(actionable, action_data)
      end
    end
  end

  def self.manufacture actionable, data

    if actionable.is_a? Event
      default_name = "Complete"
      default_command = "complete_event"
    end

    if actionable.is_a? Conversation
      default_name = '"Bye"'
      default_command = "complete_conversation"
    end

    Action.create(
      actionable: actionable,
      name: (data[:name] || default_name),
      command: (data[:command] || default_command),
      options: data[:options],
      key: data[:key]
    )
  end

end
