#encoding: utf-8
class PlantsController < ApplicationController  
  include DataController #stellt index, new, edit, update, create zur verfügung
  before_action :login_required
  layout "application"
  NAME = 'Anlage'
  PLURAL = 'Anlagen'
  LINK = 'https://wiki.e-kommu.de/index.php/Anlagen_%28Abwasserbehandlungsanlagen%29'

  def update_plant_agg_percent
    @gen = gen
    try_update = @gen.update_plant_agg_percent(params[:agglomeration_id], params[:id], params[:percent])
    if try_update
      render :json => {'status': 'OK'}
    else
      render :json => {'status': 'ERROR'}
    end
  end

  def agg_select(id, locked = false)

    sql_statement = "SELECT agg.agg_key || ' - ' || agg.ag_name as title,
        aggpl.agg_percent_plant as percent,
        agg.id as id,
        CASE WHEN agg.agg_state_active=0 OR agg.ag_to_be_reported=0 THEN true
        ELSE false
        END as \"invalid\"
      FROM agglomerations agg
      LEFT JOIN agglomerations_plants aggpl ON agg.id = aggpl.agglomeration_id
      LEFT JOIN plants pl ON pl.id = aggpl.plant_id
      WHERE pl.id = ?
      ORDER BY agg.agg_key"
    aggs = ActiveRecord::Base.execute_sql(sql_statement, id).to_a

    return render_to_string( :partial => 'plants/aggs', :locals => {:aggs => aggs, :id => id, :locked => locked ? 'true' : 'false'} ).html_safe, aggs.length, locked
  end

  def aggs_select(id)
    return '<span style="color:#df6c00">
              Um eine Agglomeration zuzuordnen, verwenden Sie bitte das Bearbeiten-Formular der Agglomeration. <br>
              Das Zuordnen ist aber erst möglich, wenn die Anlage und die Agglomeration bereits erstellt wurden.
            </span>' if id.nil?
    sql_statement = "SELECT ag.agg_key || ' - ' || ag.ag_name as title,
        ag.id as id,
        ap.agg_percent_plant as percent
      FROM agglomerations_plants ap
      LEFT JOIN agglomerations ag ON ag.id = ap.agglomeration_id
      WHERE plant_id = ?
      ORDER BY ag.agg_key"
    aggs = ActiveRecord::Base.execute_sql(sql_statement,id).to_a
    return render_to_string( :partial => 'plants/aggs', :locals => {:aggs => aggs, :id => id} ).html_safe
  end

  def aggs_select_with_add(id)
    return '<span style="color:#df6c00">
              Um eine Agglomeration zuzuordnen, verwenden Sie bitte das Bearbeiten-Formular der Agglomeration. <br>
              Das Zuordnen ist aber erst möglich, wenn die Anlage und die Agglomeration bereits erstellt wurden.
            </span>' if id.nil?
    sql_statement = "SELECT ag.agg_key || ' - ' || ag.ag_name as title,
        ag.id as id,
        ap.agg_percent_plant as percent
      FROM agglomerations_plants ap
      LEFT JOIN agglomerations ag ON ag.id = ap.agglomeration_id
      WHERE plant_id = ?
      ORDER BY ag.agg_key"
    aggs = ActiveRecord::Base.execute_sql(sql_statement,id).to_a
    return render_to_string( :partial => 'plants/aggs_add', :locals => {:aggs => aggs, :id => id} ).html_safe
  end

  def show_agg_fields

    @show_all = params[:show_all] == 'true'
    @agg_possibs = get_agg_possibs

    respond_to do |format|
      format.html
      format.js
    end
  end

  def get_agg_possibs
    show_all = params[:show_all] == 'true'
    sql_statement = "SELECT agg_key || ' - ' || ag_name as title,
                            agg_key,
                            ag_name,
                            agg.id as id
        FROM agglomerations agg
        JOIN model.reporting_periods rp ON agg.date_to = rp.date_to and rp.state = 1"
    sql_statement << "
        JOIN plants pl ON agg.federal_state_id = pl.federal_state_id AND pl.id = #{params[:id]}" unless show_all
    filter_text = params[:filter_text]
    sql_statement << "
        AND (agg.agg_key ILIKE '%#{filter_text}%' OR agg.agg_name ILIKE '%#{filter_text}%')"unless filter_text.blank?
    sql_statement << "
        ORDER BY agg_key"
    return ActiveRecord::Base.connection.query(sql_statement) #query liefert integer indizierten array, was für options_for_select hilfreich ist
  end

  def get_agg_possibs_json
    render :partial => 'layouts/filter_table', :locals => {:options => get_dp_possibs}
  end

  def hide_agg_fields
    render :html => aggs_select_with_add(params[:id])
  end

  def add_agg
    @gen = gen
    try, msg = @gen.insert_plant_to_agglomeration(params[:agglomeration_id],params[:plant_id],params[:percent],true)

    if try
      flash[:plant_notice] = msg.html_safe
    else
      if msg
        flash[:plant_error] = msg.html_safe
      else
        flash[:plant_error] = 'Die Agglomeration konnte der Anlage nicht hinzugefügt werden.'
      end
    end

    render :text => aggs_select_with_add(params[:plant_id])

  end

  def delete_agg

    @gen = gen
    try, error_msg = @gen.delete_plant_from_agglomeration(params[:agglomeration_id],params[:id])

    if try
      flash[:plant_notice] = 'Die Zuordnung der Agglomeration zur Anlage wurde erfolgreich aufgehoben.'.html_safe
    else
      if error_msg
        flash[:plant_error] = error_msg.html_safe
      else
        flash[:plant_error] = 'Die Zuordnung der Agglomeration zur Anlage konnte nicht aufgehoben werden.'.html_safe
      end
    end

    render :text => aggs_select_with_add(params[:id])
  end


  def dps_select(id)
    return '<span style="color:#df6c00">
              Um eine Einleitstelle zuzuordnen, verwenden Sie bitte das Bearbeiten-Formular der Einleitstelle. <br>
              Das Zuordnen ist aber erst möglich, wenn die Anlage und die Einleitstelle bereits erstellt wurden.
            </span>' if id.nil?
    sql_statement = "SELECT dp.dp_key || ' - ' || dp.dp_name as title,
        dp.id as id
      FROM discharge_points dp
      WHERE plant_id = ?
      ORDER BY dp.dp_key"
    dps = ActiveRecord::Base.execute_sql(sql_statement, id).to_a
    return render_to_string( :partial => 'plants/dps', :locals => {:dps => dps, :id => id} ).html_safe
  end

  def dps_select_with_add(id)
    return '<span style="color:#df6c00">
              Um eine Einleitstelle zuzuordnen, verwenden Sie bitte das Bearbeiten-Formular der Einleitstelle. <br>
              Das Zuordnen ist aber erst möglich, wenn die Anlage und die Einleitstelle bereits erstellt wurden.
            </span>' if id.nil?
    sql_statement = "SELECT dp.dp_key || ' - ' || dp.dp_name as title,
        dp.id as id
      FROM discharge_points dp
      WHERE plant_id = ?
      ORDER BY dp.dp_key"
    dps = ActiveRecord::Base.execute_sql(sql_statement, id).to_a
    return render_to_string( :partial => 'plants/dps_add', :locals => {:dps => dps, :id => id} ).html_safe
  end

  def get_successor_possibs
    all = params[:show_all] == 'true'
    sql_statement = "SELECT coalesce(pl.pl_key,'') || ' - ' || coalesce(pl.pl_name,'') as title,
                            pl.pl_key,
                            pl.pl_name,
                            pl.id as id
        FROM plants pl
        JOIN model.reporting_periods rp ON pl.date_to = rp.date_to and rp.state = 1
        WHERE pl.pl_state_active = 0 
          AND (#{all ? 'true' : 'false'} OR ROW(pl.federal_state_id) = (SELECT federal_state_id FROM plants WHERE id = ?))
          AND (pl.pl_key ILIKE ? OR pl.pl_name ILIKE ?)
        ORDER BY pl.pl_key"
    filter_text = "%#{params[:filter_text]}%"
    return ActiveRecord::Base.query_sql(sql_statement,params[:id],filter_text,filter_text) #query liefert integer indizierten array, was für options_for_select hilfreich ist
  end

  def successor_select(id)
    sql_statement = "SELECT coalesce(pl.pl_key,'') || ' - ' || coalesce(pl.pl_name,'') as title,
        pl.id as id
      FROM plants_successors s
      LEFT JOIN plants pl ON pl.id = s.plant_pre_id
      WHERE plant_succ_id = ?
      ORDER BY pl.pl_key"
    successors = ActiveRecord::Base.execute_sql(sql_statement, id).to_a
    return render_to_string( :partial => 'layouts/successor_btn', :locals => {:successors => successors, :id => id} ).html_safe
  end

  def show_dp_fields

    @show_all = params[:show_all] == 'true'
    @dp_possibs = get_dp_possibs
    puts @dp_possibs[0][0]
    respond_to do |format|
      format.html
      format.js
    end
  end

  def hide_dp_fields
    render :html => dps_select_with_add(params[:id])
  end

  def get_dp_possibs
    show_all = params[:show_all] == 'true'
    sql_statement = "SELECT dp_key || ' - ' || dp_name as title,
                            dp_key,
                            dp_name,
                            dp.id as id,
                            dp.plant_id as plant_id
        FROM discharge_points dp
        JOIN model.reporting_periods rp ON dp.date_to = rp.date_to and rp.state = 1"
    sql_statement << "
        JOIN plants pl ON dp.federal_state_id = pl.federal_state_id AND pl.id = #{params[:id]}" unless show_all
    filter_text = params[:filter_text]
    sql_statement << "
        AND (dp.dp_key ILIKE '%#{filter_text}%' OR dp.dp_name ILIKE '%#{filter_text}%')"unless filter_text.blank?
    sql_statement << "
        ORDER BY dp_key"
    return ActiveRecord::Base.connection.query(sql_statement) #query liefert integer indizierten array, was für options_for_select hilfreich ist
  end

  def get_dp_possibs_json
    render :partial => 'layouts/filter_table', :locals => {:options => get_dp_possibs}
  end

  # plant selection code - übernommen aus agglomerations
  def dp_select(id, locked = false)

    sql_statement = "SELECT dp.dp_key || ' - ' || dp.dp_name as title,
        dp.id as id,
        CASE WHEN dp.dp_state_active=0 OR dp.dp_to_be_reported=0 THEN true
        ELSE false
        END as \"invalid\"
      FROM discharge_points dp
      LEFT JOIN plants pl ON pl.id = dp.plant_id
      WHERE dp.plant_id = ?
      ORDER BY dp.dp_key"
    discharge_points = ActiveRecord::Base.execute_sql(sql_statement, id).to_a

    return render_to_string( :partial => 'plants/dps_btn', :locals => {:discharge_points => discharge_points, :id => id, :locked => locked ? 'true' : 'false'} ).html_safe, discharge_points.length, locked
  end

  def add_dp
    @gen = gen
    try, msg = @gen.set_plant_of_discharge_point(params[:dp_id], params[:id], true)

    if try
      flash[:plant_notice] = msg.html_safe
    else
      if msg
        flash[:plant_error] = msg.html_safe
      else
        flash[:plant_error] = 'Die Einleitstelle konnte der Anlage nicht hinzugefügt werden.'
      end
    end

    render :text => dps_select_with_add(params[:id])
  end

  def delete_dp

  @gen = gen
  try, error_msg = @gen.delete_plant_from_discharge_point(params[:dp_id],params[:id], true)

  if try
    flash[:plant_notice] = 'Die Zuordnung der Einleitstelle zur Anlage wurde erfolgreich aufgehoben.'.html_safe
  else
    if error_msg
      flash[:plant_error] = error_msg.html_safe
    else
      flash[:plant_error] = 'Die Zuordnung der Einleitstelle zur Anlage konnte nicht aufgehoben werden.'.html_safe
    end
  end

  render :text => dps_select_with_add(params[:id])
end


  protected

  def gen
     @datensatz = 'plants'
    return Generica.new(@datensatz, session[:user])
  end

end
