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 create
    return if not already_registered?(request.remote_ip)

    mash_params = params[:mash].clone
    logger.info("Got params: #{params.inspect}")

    requester = Requester.find_by_ip(request.remote_ip)
    tournament = requester.mash_tournaments.first
    mash_params[:tournament_id] = tournament.id

    logger.info("Creating mash with: #{mash_params.inspect}")
    @mash = Mash.new(mash_params)

    @winner = Map.find(@mash.winner_id.to_i)
    @winner.points += 1

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

    respond_to do |format|
      if @winner.save && @mash.save
        flash[:notice] = 'Mash was successfully created.'
        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
