class VotesController < ApplicationController
  
  before_action :authenticate_user!, except: [:index]
  
  def index
    @candidates = Candidate.all.group_by(&:position_id)

  end
  def profiles
    render "/votes/profiles.html.erb"
  end

  def vote
      @vote = Vote.new
      @candidates = Candidate.all.group_by(&:position_id)

  end

  def confirm_vote
    @vote = Vote.new(vote_params)
    @vote.user = current_user

    voted = false
    current_user.votes.each do |v|
      if @vote.candidate.position.id == v.candidate.position.id
        voted = true
      end
    end

    if voted == true
      redirect_to "/"
    else
      if @vote.save(vote_params)
        redirect_to :vote
      else
        render :vote
      end
    end
  end

  def vote_history
    @votes = current_user.votes
  end

  private
    def vote_params
      params.require(:vote).permit!
    end
end
