class PpaParticipativo::Cidadaos::RegistrationsController < Devise::RegistrationsController
	before_action :verifica_liberacao_do_ppa_participativo, only: [:new, :create]

	def new
		build_resource({})
		yield resource if block_given?
		respond_with resource
	end

	def create
		build_resource(sign_up_params)

		resource.save
		yield resource if block_given?
		if resource.persisted?
			if resource.active_for_authentication?
				sign_up(resource_name, resource)
				set_flash_message! :notice, :signed_up
				respond_with resource, location: after_sign_up_path_for(resource)
			else
				set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
				expire_data_after_sign_in!
				respond_with resource, location: after_inactive_sign_up_path_for(resource)
			end
		else
			@ppa_atual = Ppa::Ppa.find_by(ppa_participativo_ativo: true)
			clean_up_passwords resource
			set_minimum_password_length
			respond_with resource
		end
	end

	def edit
		if params[:commit] == "Aceitar termos de uso"
			@cidadao.update_columns(aceitou_os_termos_de_uso: true)
			redirect_to ppa_participativo_participe_path
		elsif params[:commit] == "Recusar termos de uso"
			@cidadao.aceitou_os_termos_de_uso = false
			@cidadao.save
			redirect_to ppa_participativo_participe_path
		else
		@brasao = Configuracao.last.brasao(:thumb)
		@ppa_atual = Ppa::Ppa.find_by(ppa_participativo_ativo: true)
		end
	end

	def after_sign_up_path_for(resource)
		stored_location_for(:cidadao) || ppa_participativo_participe_path
	end

	def after_inactive_sign_up_path_for(resource)
		ppa_participativo_path
	end

	def after_update_path_for(resource)
		ppa_participativo_participe_path
	end

	def update_resource(resource, params)
		@ppa_atual = Ppa::Ppa.find_by(ppa_participativo_ativo: true)
		if params[:password].blank? && params[:password_confirmation].blank?
			params.delete(:password)
			params.delete(:password_confirmation)
		end

		resource.update(params)
	end

	private
	def verifica_liberacao_do_ppa_participativo
		@ppa_atual = Ppa::Ppa.find_by(ppa_participativo_ativo: true)
		redirect_to ppa_participativo_path unless @ppa_atual
	end
end
