#encoding: utf-8
class DischargePointsController < ApplicationController
  include DataController #stellt index, new, edit, update, create zur verfügung
  before_action :login_required
  layout "application"
  
  NAME = 'Einleitstelle'
  PLURAL = 'Einleitstellen'
  LINK = 'https://wiki.e-kommu.de/index.php/Einleitstellen'


  def get_successor_possibs
    all = params[:show_all] == 'true'
    sql_statement = "SELECT coalesce(dp.dp_key,'') || ' - ' || coalesce(dp.dp_name,'') as title,
                            dp.dp_key,
                            dp.dp_name,
                            dp.id as id
        FROM discharge_points dp
        JOIN model.reporting_periods rp ON dp.date_to = rp.date_to and rp.state = 1
        WHERE dp.dp_state_active = 0 
          AND (#{all ? 'true' : 'false'} OR ROW(dp.federal_state_id) = (SELECT federal_state_id FROM discharge_points WHERE id = ?))
          AND (dp.dp_key ILIKE ? OR dp.dp_name ILIKE ?)
        ORDER BY dp.dp_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(dp.dp_key,'') || ' - ' || coalesce(dp.dp_name,'') as title,
        dp.id as id
      FROM discharge_points_successors s
      LEFT JOIN discharge_points dp ON dp.id = s.discharge_point_pre_id
      WHERE discharge_point_succ_id = ?
      ORDER BY dp.dp_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 get_plant_id(id)
    sql_statement = "
      SELECT pl.id as plant_id, pl.pl_key as plant_key, pl.pl_name as plant_name
      FROM plants pl
      RIGHT JOIN discharge_points dp on dp.plant_id = pl.id
      WHERE dp.id = ? LIMIT 1"
    result_set = ActiveRecord::Base.execute_sql(sql_statement, params[:id]).to_a
    return render_to_string( :partial => 'discharge_points/plant_field', :locals => {:plant => result_set[0]}).html_safe, 1
  end

  def get_plant(id)
    sql_statement = "
      SELECT pl.id as plant_id, pl.pl_key as plant_key, pl.pl_name as plant_name
      FROM plants pl
      RIGHT JOIN discharge_points dp on dp.plant_id = pl.id
      WHERE dp.id = ? LIMIT 1"
    result_set = ActiveRecord::Base.execute_sql(sql_statement, params[:id]).to_a
    if result_set.count == 1
      return result_set[0]
    end
    return nil
  end

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

    sql_statement = "SELECT pl.pl_key || ' - ' || pl.pl_name as title,
        pl.id as id, dp.locked AS dp_locked,
        CASE WHEN pl.pl_state_active=0 OR pl.pl_to_be_reported=0 THEN true
        ELSE false
        END as \"invalid\"
      FROM plants pl
      LEFT JOIN discharge_points dp ON pl.id = dp.plant_id
      WHERE dp.plant_id = ?
      ORDER BY pl.pl_key"
    plants = ActiveRecord::Base.execute_sql(sql_statement, id).to_a

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

  def plants_select_with_add(id)
    str, count, locked = plants_select(id)
    # m_n = ActiveRecord::Base.query_sql("select fs.uses_m_n_rel from public.agglomerations a
    #   join public.l_federal_state fs on a.federal_state_id = fs.id
    #   where a.id = ?", id)[0][0]=='t'
    # if m_n || count == 0
    #     mode = 'add'
    # elsif
    plant = get_plant(id)
    str << render_to_string( :partial => 'discharge_points/plants_add_btn', :locals => {:id => id, :locked => locked ? 'true' : 'false', :plant => plant} ).html_safe
    return str
  end


  def show_plant_fields

    @show_all = params[:show_all] == 'true'
    @plant_possibs = get_plant_possibs

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

  def hide_plant_fields
    render :html => plants_select_with_add(params[:id])
  end

  def get_plant_possibs
    show_all = params[:show_all] == 'true'
    sql_statement = "SELECT pl_key || ' - ' || pl_name as title,
                            pl_key,
                            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"
    sql_statement << "
        JOIN discharge_points dp ON dp.federal_state_id = pl.federal_state_id AND dp.id = #{params[:id]}" unless show_all
    filter_text = params[:filter_text]
    sql_statement << "
        AND (pl.pl_key ILIKE '%#{filter_text}%' OR pl.pl_name ILIKE '%#{filter_text}%')"unless filter_text.blank?
    sql_statement << "
        ORDER BY pl_key"
    return ActiveRecord::Base.connection.query(sql_statement) #query liefert integer indizierten array, was für options_for_select hilfreich ist
  end

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

  def add_plant
    @gen = gen
    try, msg = @gen.set_plant_of_discharge_point(params[:id], params[:plant_id])

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

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

  def delete_plant

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

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

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

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

end
