class TeamsController < ApplicationController
  before_action :admin_authenticate, :only=>['admin_index']
#   before_filter :authenticate_team!, :except => ['index']
#   before_filter :get_user, :only => [:index,:new,:edit]
#   before_filter :accessible_roles, :only => [:new, :edit, :show, :update, :create]
#   load_and_authorize_resource :only => [:show,:new,:destroy,:edit,:update]

  # GET /teams
  def index
    redirect_to :action=>'public_index'
  end

  def admin_index
    @teams = Team.all
  end

  def public_index
    @teams = Team.all.select{|t| t.letos_prihlasen}
  end

  def email_index
    @teams = Team.all.select{|t| t.letos_prihlasen}
  end
  
  # GET /teams/1
  def show
#     @team = Team.find(params[:id])
    redirect_to :action => "edit"
  end

  def prihlas
    @team = Team.find(params[:id])
    @team.prihlasit_na_letosek!
    @team.save(validate: false)
    redirect_to '/teams/edit'
  end
  
  # GET /teams/new
  def new
    @team = Team.new
  end

  # GET /teams/1/edit
  def edit
    @team = Team.find(params[:id])
  end

  # PUT /teams/1
  # PUT /teams/1.xml
  def update
    @team = Team.find(params[:id])
    if params[:team][:password]=='' 
      params[:team].delete(:password)
      params[:team].delete(:password_confirmation)
    end

    respond_to do |format|
      if @team.update_attributes(team_params)
        format.html { redirect_to(@team, :notice => 'Team was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @team.errors, :status => :unprocessable_entity }
      end
    end
  end


  # POST /teams
  def create
    @team = Team.new(team_params)

    if @team.save
      redirect_to(@team, :notice => 'team was successfully created.')
    else
      render :action => "new"
    end
  end

  # DELETE /teams/1
  def destroy
    render plain: "Pro odhlášení nás prosím kontaktujte emailem na 4p@hrejsi.cz"
#    @team = Team.find(params[:id])
#    @team.destroy

#    redirect_to(teams_url)
  end

  def mailsent
  end
  
  protected
  
  def admin_authenticate
    authenticate_or_request_with_http_basic "Administratorsky login je 4p, heslo znaji autorizovani lide" do |username, password|
      username == "4p" && password == "pppp"
    end
  end

  private 
  def team_params
    params.require(:team).permit(Team.allowed_params)
  end

end
