class MashesController < ApplicationController
  def redirect_to_new
    flash[:notice] = 'Sneaky pete.'
    redirect_to(:action => 'new')
  end

  alias_method :index, :redirect_to_new
  alias_method :show, :redirect_to_new

  def new
    return if not already_registered?(request.remote_ip)

    requester = Requester.find_by_ip(request.remote_ip)
    @mash = requester.current_tournament.next_unplayed_mash

    if not @mash
      flash[:notice] = "You're done!"
      redirect_to requester.current_tournament, :action => 'show'
      return
    end

    respond_to do |format|
      format.html
    end
  end

  def update
    return if not already_registered?(request.remote_ip)
    logger.info("Got params: #{params.inspect}")

    @mash = Mash.find(params[:id])
    @mash.winner = Map.find((params[:mash][:winner_id] || -1).to_i)

    logger.info("About to save #{@mash.inspect}")

    respond_to do |format|
      if @mash.save
        flash[:notice] = 'Mashed!'
        format.html { redirect_to(:action => 'new') }
      else
        format.html { render :action => 'new' }
      end
    end
  end

  def already_registered?(ip)
    if not Requester.find_by_ip(ip)
      redirect_to :controller => :mash_tournaments, :action => 'new'
      return false
    end

    true
  end
end