module GraficosConcern extend ActiveSupport::Concern
	require 'gruff'
	require 'tmpdir'
	include GeradorDeImagemBase64Concern

	def grafico_pizza titulo, itens
		graph = Gruff::Pie.new
		graph.title = titulo
		graph.title_font_size = 25
		graph.legend_font_size = 18
		graph.theme = {
			:colors => %w(#ffa726 #039be5 #66bb6a #f44336 #bdbdbd #ec407a #ab47bc #ffee58 #212121 magenta coral cyan lightsalmon mediumaquamarine palegreen plum yellowgreen teal olive indigo  navy blueviolet chartreuse darkcyan),
			:marker_color => 'blue',
			:background_colors => 'white'
		}
		montante = retorna_total itens
		limite_atual = 1
		quantidade_limite_de_itens = verifica_limite_de_itens(itens, limite_atual, montante)
		while quantidade_limite_de_itens > 5
			limite_atual *= 2
			quantidade_limite_de_itens = verifica_limite_de_itens(itens, limite_atual, montante)
		end

		piso_porcentagem = montante * ( limite_atual * 0.01 )
		outros = 0

		itens.each do |valor|
			if valor[:quantidade] < piso_porcentagem
				outros += valor[:quantidade]
			else
				graph.data(valor[:nome], valor[:quantidade])
			end
		end

		graph.data("Outros", outros) if outros > 0

		cria_grafico_e_salva_na_pasta(titulo, graph)
	end

	def retorna_total itens
		total = 0
		itens.each do |item|
			total += item[:quantidade]
		end
		total
	end

	def verifica_limite_de_itens itens, limite_atual, total
		itens_no_limite = 0
		itens.each { |item|
			porcentagem = total > 0 ? ((item[:quantidade].to_f / total.to_f) * 100).round(2) : 0
			itens_no_limite += 1 if porcentagem >= limite_atual
		}
		itens_no_limite
	end

	def grafico_barra titulo, itens
		graph = Gruff::SideBar.new 1000
		graph.hide_legend = true
		graph.title = titulo
		graph.marker_font_size = 12
		graph.label_formatting = "%.2f"
		graph.bar_spacing = 0.5
		graph.use_data_label = true

		valor_maximo = itens.max_by{ |item| item[:quantidade] }[:quantidade]
		graph.maximum_value = numero_valido(valor_maximo)
		graph.minimum_value = 0
		graph.x_axis_increment = 1

		graph.theme = {
			:colors => %w(#ffa726 #039be5 #66bb6a #f44336 #bdbdbd #ec407a #ab47bc #ffee58 #212121 magenta coral cyan lightsalmon mediumaquamarine palegreen plum yellowgreen teal olive indigo  navy blueviolet chartreuse darkcyan),
		 :marker_color => 'black',
		 :background_colors => 'white'
		}

		itens_labels = itens.each.with_index.inject({}){|hash_final,(item,index)|
			hash_final.merge(index => item[:nome])
		}

		itens.each do |valor|
			graph.data(valor[:nome], [valor[:quantidade]])
		end

		graph.labels = itens_labels

		cria_grafico_e_salva_na_pasta(titulo, graph)
	end

	def cria_grafico_e_salva_na_pasta(titulo, graph)
		Dir.mkdir("tmp/cache/graficos/") unless File::directory?("tmp/cache/graficos/")
		graph.write("tmp/cache/graficos/" + titulo.parameterize.underscore + ".jpg")
		gerar_imagem_em_base64("tmp/cache/graficos/" + titulo.parameterize.underscore + ".jpg")
	end

	def numero_valido numero
		numero = numero.ceil
		while !(numero % 5 == 0)
			numero += 1
		end
		numero
	end
end
