#encoding: utf-8
class PlantsAbfrageController < AbstractAbfrageController
  include ActiveModel::AttributeAssignment
  before_action :login_required
  layout "application"
  NAME = 'Anlage'
  PLURAL = 'Anlagen'
  
  attr_accessor :conditions, :condition_parameters

  include ApplicationHelper

  def filter_columns
    @anlagen = Generica.new('plants', session[:user])
    session[:pl_query] = Hash.new()
    session[:pl_query][:jahr] = params[:jahr]
    session[:pl_query][:fertigstellung] = [params[:fertigstellung], params[:fert]]
    session[:pl_query][:ausbaugroesse] = [params[:ausbaugroesse], params[:ausbau]]
    session[:pl_query][:belastung] = [params[:belastung], params[:belast]]
    session[:pl_query][:konform] = params[:konform]
    session[:pl_query][:csb_erlaubnis] = [params[:csb_erlaubnis], params[:csb_erlaub]]
    session[:pl_query][:csb_eingeh] = params[:csb_eingeh]
    session[:pl_query][:bsb_erlaubnis] = [params[:bsb_erlaubnis], params[:bsb_erlaub]]
    session[:pl_query][:bsb_eingeh] = params[:bsb_eingeh]
    session[:pl_query][:n_erlaubnis] = [params[:n_erlaubnis], params[:n_erlaub]]
    session[:pl_query][:n_eingeh] = params[:n_eingeh]
    session[:pl_query][:p_erlaubnis] = [params[:p_erlaubnis], params[:p_erlaub]]
    session[:pl_query][:p_eingeh] = params[:p_eingeh]
    session[:pl_query][:ausbauten] = params[:ausbauten]
    session[:pl_query][:name] = params[:name]
    session[:pl_query][:id] = params[:id]
    session[:pl_query][:eu_key] = params[:eu_key]
    session[:pl_query][:federal_state_id] = params[:federal_state_id]
  end

  def index
    @reporting_periods = ActiveRecord::Base.connection.execute("SELECT key_report FROM reporting_periods ORDER BY key_report").to_a.collect { |e| [e['key_report']]  }
    @reporting_periods.unshift ["Alle", ""]
    @act_period = ActiveRecord::Base.connection.execute("SELECT key_report FROM reporting_periods WHERE state = 1 LIMIT 1").first['key_report']

    @federal_states = ActiveRecord::Base.connection.execute("SELECT id, name FROM l_federal_state WHERE id < 18 ORDER BY name").to_a.collect  { |e| [e['name'], e['id']]  }
    @federal_states.unshift ["Alle", ""]
    @default_federal_state = theUser(session).get_default_federal_state

    @compliance_levels = Compliance.order(:position).to_a.collect { |c| [c['description'],c['id']] }.unshift(["Alle anzeigen",-1])
  end

  def result
    session[:pl_query][:columns] = params[:columns] unless params[:columns].nil?
    @datensatz = 'plants'
    @where = 'pl_query' #wird benötigt für csv-export
    spalten = session[:pl_query][:columns] #doesn't need escaping or anything because generica ignores any column it doesn't know
    @gen = Generica.new(@datensatz, session[:user])
    @user = theUser(session)
    if params['amount'].to_i > 0
      @user.update_attributes(:rows_per_page => params['amount'])
    end
    form_where #sets @condition*, and could be included inline
    @data, @order = @gen.all(@conditions, @condition_parameters, spalten, @user.rows_per_page, params['offset'])

    render :template => 'layouts/list'
  end

  def where_erlaubniswerte (schluessel, spalte)
    unless @@sitzung[:pl_query][schluessel][0].blank?
      @conditions += "and #{spalte} #{@@sitzung[:pl_query][schluessel][1].to_i==1?'>':'<'} ? "
      @condition_parameters << @@sitzung[:pl_query][schluessel][0]
    end
  end

  def subwhere_int (schluessel, spalte)
    unless @@sitzung[:pl_query][schluessel].to_i < 0
      @condition_parameters << @@sitzung[:pl_query][schluessel]
      return "#{spalte} = ? or "
    end
    return ''
  end

  def form_where()
    # Die Bundesländer werden nun von generica.all automatisch der where-Clause vorangestellt
    @conditions = " "
    @condition_parameters = []
    #einbau der Abfragen
    @@sitzung = session
    where_equals(session[:pl_query][:jahr],'plants.rep_code')
    where_like(session[:pl_query][:name],'plants.pl_name')
    where_like(session[:pl_query][:id],'plants.pl_key')
    where_erlaubniswerte(:fertigstellung, "floor(plants.pl_cdate/10000)")
    where_erlaubniswerte(:ausbaugroesse, "plants.pl_odc")
    where_erlaubniswerte(:belastung, "plants.pl_nload")
    where_erlaubniswerte(:csb_erlaubnis, "plants.pl_cod")
    where_erlaubniswerte(:bsb_erlaubnis, "plants.pl_bod")
    where_erlaubniswerte(:n_erlaubnis, "plants.pl_n")
    where_erlaubniswerte(:p_erlaubnis, "plants.pl_p")
    where_like(session[:pl_query][:eu_key],'plants.pl_eu_key')
    where_equals(session[:pl_query][:federal_state_id],'plants.federal_state_id')

    #diese Abfragen werden or verknüpft
    sub_where = ""
    sub_where += subwhere_int(:konform, "plants.pl_overall_compliant")
    sub_where += subwhere_int(:csb_eingeh, "plants.pl_cod_anh1_id")
    sub_where += subwhere_int(:bsb_eingeh, "plants.pl_bod_anh1_id")
    sub_where += subwhere_int(:n_eingeh, "plants.pl_n_anh1_id")
    sub_where += subwhere_int(:p_eingeh, "plants.pl_p_anh1_id")
    unless sub_where.empty?
      @conditions += "AND (#{sub_where}false)"
    end
 
    unless session[:pl_query][:ausbauten].nil? || session[:pl_query][:ausbauten].delete_if{|c| @gen.columns.include?(c)}.empty?
      @conditions += "AND (" + session[:pl_query][:ausbauten].join(" = 1 or ") + " = 1)"
    end
    @@sitzung = nil
  end

  def self.form_where_mit_parameter(session)
    tmp = self.new

    # Die Bundesländer werden nun von generica.all automatisch der where-Clause vorangestellt
    tmp.conditions = " "
    tmp.condition_parameters = []

    #einbau der Abfragen
    @@sitzung = session
    tmp.where_equals(session[:pl_query][:jahr],'plants.rep_code')
    tmp.where_like(session[:pl_query][:name],'plants.pl_name')
    tmp.where_like(session[:pl_query][:id],'plants.pl_key')
    tmp.where_like(session[:pl_query][:eu_key],'plants.pl_eu_key')
    tmp.where_equals(session[:pl_query][:federal_state_id],'plants.federal_state_id')
    tmp.where_erlaubniswerte(:fertigstellung, "floor(plants.pl_cdate/10000)")
    tmp.where_erlaubniswerte(:ausbaugroesse, "plants.pl_odc")
    tmp.where_erlaubniswerte(:belastung, "plants.pl_nload")
    tmp.where_erlaubniswerte(:csb_erlaubnis, "plants.pl_cod")
    tmp.where_erlaubniswerte(:bsb_erlaubnis, "plants.pl_bod")
    tmp.where_erlaubniswerte(:n_erlaubnis, "plants.pl_n")
    tmp.where_erlaubniswerte(:p_erlaubnis, "plants.pl_p")

    #diese Abfragen werden or verknüpft
    sub_where = ""
    sub_where += tmp.subwhere_int(:konform, "plants.pl_overall_compliant")
    sub_where += tmp.subwhere_int(:csb_eingeh, "plants.pl_cod_anh1_id")
    sub_where += tmp.subwhere_int(:bsb_eingeh, "plants.pl_bod_anh1_id")
    sub_where += tmp.subwhere_int(:n_eingeh, "plants.pl_n_anh1_id")
    sub_where += tmp.subwhere_int(:p_eingeh, "plants.pl_p_anh1_id")
    unless sub_where.empty?
      tmp.conditions += "AND (#{sub_where}false)"
    end
 
    unless session[:pl_query][:ausbauten].nil? || session[:pl_query][:ausbauten].delete_if{|c| @gen.columns.include?(c)}.empty?
      tmp.conditions += "AND (" + session[:pl_query][:ausbauten].join(" = 1 or ") + " = 1)"
    end

    return [ tmp.conditions, tmp.condition_parameters ]
  end

  def self.form_spalten(session)
    return session[:pl_query][:columns]
  end

  def edit()
    redirect_to :controller => :plants, :action => :edit, :id => params[:id]
  end

  def delete
    redirect_to :controller => :plants, :action => :delete, :id => params[:id]
  end

  def heading
    return self.class::PLURAL
  end

end
