module Tcm
	class ArquivosController < ApplicationController
		include ControllerConcern
		before_action :authenticate_usuario!
		before_action :autoriza_usuario!
		before_action :set_arquivo, only: [:download, :processar, :destroy]

		# GET /tcm/arquivos
		def index
			@q = Arquivo.order(:id).search(params[:q])
			@arquivos = @q.result(distinct: false).paginate(page: params[:page], per_page: 10)
		end

		def download
			send_data(@arquivo.conteudo, filename: @arquivo.nome, type: 'text/plain', :disposition => :attachment)
		end

		def destroy
			lote = @arquivo.lote
			mensagem = apaga_e_retorna_mensagem(@arquivo)
			redirect_to tcm_lote_path(lote) + "?tab=arquivos_importados", mensagem
		end

		def processar
			if @arquivo.processar == true
				render json: {'result': 'success', 'message': 'Arquivo gerado com sucesso.'}
			else
				render json: {'result': 'fail', 'message': 'Não foi possível gerar o arquivo.'}
			end
		end

		#PATCH /tcm/arquivos/importar_arquivo_externo/:nome/:lote_id/:conteudo
		def importar_arquivo_externo
			@arquivo = Arquivo.new(nome: params[:nome], lote_id: params[:lote_id], conteudo: params[:conteudo], importado: true)
			@arquivo.save(validate: false)

			redirect_to tcm_lote_path(params[:lote_id])
		end

		private
		def set_arquivo
			@arquivo = Arquivo.find( params[:id] )
		end
	end
end
