# -*- coding: utf-8 -*-
class AbfallManager

  def initialize(lang)
    @data = {}
    @lang = lang
    if lang == 'de'
      @abfall_template = ERB.new(File.read('templates/_abfall.erb'))
    elsif lang == 'en'
      @abfall_template = ERB.new(File.read('templates/_abfall_en.erb'))
    end
    @data[:gefin] = {:ver => FloatTrackingArray.new(['menge']), :bes => FloatTrackingArray.new(['menge']), :sum => 0}
    @data[:gefaus] = {:ver => FloatTrackingArray.new(['menge']), :bes => FloatTrackingArray.new(['menge']), :sum => 0}
    @data[:nigef] = {:ver => FloatTrackingArray.new(['menge']), :bes => FloatTrackingArray.new(['menge']), :sum => 0}
    @data[:gehnig] = []
    @data[:gehgef] = []
    @data[:geheim] = []
  end

  def push(row)
    abf = Entry.new(row,'p_vabf',@lang)
    unless abf.geheimk.empty?
      if abf['abfart_id'] == 2
        @data[:gehnig] |= abf.geheimk
      else
        @data[:gehgef] |= abf.geheimk
      end
      @data[:geheim] |= abf.geheimk
    else
      container = get_container(abf)
      if abf['verbes_id'] == 2
        container[:ver].push(abf,['menge'])
      else
        container[:bes].push(abf,['menge'])
      end
      container[:sum] += abf['menge']
    end
  end

  def [](identifier)
    return @data[identifier]
  end

  def render_compartment(identifier)
    container = self[identifier]
    @abfall_template.result(binding)
  end
  

  def sort
    @data[:gefin][:ver].sort_by('menge')
    @data[:gefaus][:ver].sort_by('menge')
    @data[:nigef][:ver].sort_by('menge')
    @data[:gefin][:bes].sort_by('menge')
    @data[:gefaus][:bes].sort_by('menge')
    @data[:nigef][:bes].sort_by('menge')
  end

  private
  def get_container(abf)
    if abf['abfart_id'] == 2
      return @data[:nigef]
    else
      if abf['aland_id'] == 2
        return @data[:gefin]
      else
        return @data[:gefaus]
      end
    end
  end
end
