module Mea::MeasuresHelper

  def add_energy_measure_link(name)
    link_to_function name do |page|
      page.insert_html :bottom, :energy_measures, :partial =>'mea/energy_measures/partial_form', :object => Mea::EnergyMeasure.new
    end
  end

  def prepear_measures measure
    times_energy = measure.energy_measures.size - Adm::Step.all.size
    times_residue = measure.residue_measures.size - ( Adm::Step.all.size * 4 )
    times_water = measure.water_measures.size - Adm::Step.all.size

    until times_energy >= 0
      measure.energy_measures.build
      times_energy += 1
    end

    until times_residue >= 0
      measure.residue_measures.build
      times_residue += 1
    end

    until times_water >= 0
      measure.water_measures.build
      times_water += 1
    end

    sort_measures_by_steps measure.water_measures
    sort_measures_by_steps measure.residue_measures
    sort_measures_by_steps measure.energy_measures

    return measure
  end

  def sort_measures_by_steps measure_array
    id_arrays = Array.new

    measure_array.each do |measure|
      id_arrays.push(measure.adm_step_id) unless measure.adm_step_id.blank?
    end

    Adm::Step.all.each_with_index do |step, index|
      exist = false
      next if measure_array[index].adm_step_id.present?
      id_arrays.each do |item|
        if item == step.id
          exist = true
          break
        end
      end
      next if exist
      measure_array[index].adm_step_id = step.id
    end
  end
end
