class Ppa::SubAreasTematicasController < ApplicationController
	include ControllerConcern
	include PpaControllersConcern

	before_action :authenticate_usuario!
	before_action :autoriza_usuario!, except: [:index]
	before_action :set_ppa_sub_area_tematica, only: [:show, :edit, :update, :destroy]
	before_action :disponibiliza_funcoes, only: [:new, :edit]

	def index
		@sub_areas_tematicas = ppa_atual.areas_tematicas.find(params[:q][:area_tematica_id_eq]).sub_areas_tematicas

		respond_to do |format|
			format.json { render json: @sub_areas_tematicas, methods: :nome }
			format.js
		end
	end

	# GET /ppa/sub_areas_tematicas/new
	def new
		@ppa_sub_area_tematica = Ppa::SubAreaTematica.new
		@ppa_sub_area_tematica.area_tematica = Ppa::AreaTematica.find( params[:area_tematica_id] )
	end

	# GET /ppa/sub_areas_tematicas/1/edit
	def edit
	end

	# POST /ppa/sub_areas_tematicas
	def create

		@ppa_sub_area_tematica = Ppa::SubAreaTematica.new(ppa_sub_area_tematica_params)
		if @ppa_sub_area_tematica.save
			redirect_to @ppa_sub_area_tematica.area_tematica, notice: 'Subárea Temática foi criada com sucesso.'
		else
			disponibiliza_funcoes
			render :new
		end
	end

	# PATCH/PUT /ppa/sub_areas_tematicas/1
	def update
		if @ppa_sub_area_tematica.update(ppa_sub_area_tematica_params)
			redirect_to @ppa_sub_area_tematica.area_tematica, notice: 'Subárea Temática foi atualizada com sucesso.'
		else
			disponibiliza_funcoes
			render :edit
		end
	end

	# DELETE /ppa/sub_areas_tematicas/1
	def destroy
		mensagem = apaga_e_retorna_mensagem(@ppa_sub_area_tematica)
		redirect_to @ppa_sub_area_tematica.area_tematica, mensagem
	end

	private
	# Use callbacks to share common setup or constraints between actions.
	def set_ppa_sub_area_tematica
		@ppa_sub_area_tematica = Ppa::SubAreaTematica.find(params[:id])
	end

	# Only allow a trusted parameter "white list" through.
	def ppa_sub_area_tematica_params
		params.require(:ppa_sub_area_tematica).permit(:area_tematica_id, :funcao_id, :nome)
	end

	def disponibiliza_funcoes
		@funcoes = Ppa::Funcao.where(ppa_id: ppa_atual.id).order(:nome)
	end
end
