class MashTournamentsController < ApplicationController
  def index
    @mash_tournaments = MashTournament.all

    respond_to do |format|
      format.html
    end
  end

  def show
    begin
      @mash_tournament = MashTournament.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      redirect_to :action => 'new' and return
    end

    if not @mash_tournament.done?
      return if should_start_mashing?(request.remote_ip)
    end

    respond_to do |format|
      format.html
    end
  end

  def new
    return if should_start_mashing?(request.remote_ip)

    @mash_tournament = MashTournament.new

    respond_to do |format|
      format.html
    end
  end

  def create
    return if should_start_mashing?(request.remote_ip)

    @mash_tournament = MashTournament.new(
      :requester => Requester.new(:ip => request.remote_ip)
    )

    respond_to do |format|
      if @mash_tournament.save && @mash_tournament.create_rounds_for_contenders(8)
        flash[:notice] = "Let's start mashing!"
        format.html { redirect_to :controller => 'mashes', :action => 'new' }
      else
        format.html { render :action => "new" }
      end
    end
  end

  private
  def should_start_mashing?(ip)
    if requester = Requester.find_by_ip(ip)
      redirect_to :controller => 'mashes', :action => 'new'
      return true
    end

    false
  end
end
