class FairyController < ApplicationController
  def mark
    instance_id, location = mark_params
    instance = Instance.find_by(public_id: instance_id)
    if params[:pwd]
      fairy = Fairy.new(location: location, instance_id: instance.id)
      fairy.save
    end

    new_instance = Instance.includes(:fairies).find(instance.id)
    render partial: "instance/fairies", locals: { instance: new_instance }
  end

  def unmark
    instance_id, location = mark_params
    if params[:pwd]
      instance = Instance.find_by(public_id: instance_id)
      Fairy.delete_by(instance_id: instance.id, location: location)
      new_instance = Instance.includes(:fairies).find(instance.id)
      render partial: "instance/fairies", locals: { instance: new_instance }
    end
  end

  def despawn
    instance_id, location = mark_params
    instance = Instance.find_by(public_id: instance_id)
    fairy = Fairy.find_by(instance_id: instance.id, location: location)
    unless fairy.is_despawned
      fairy.is_despawned = true
      fairy.save
      new_instance = Instance.includes(:fairies).find(instance.id)
      render partial: "instance/fairies", locals: { instance: new_instance }
    end
  end

  private

  def mark_params
    params.expect(:instance, :location)
  end
end
