class ApplicationController < ActionController::Base
  include StationHelper

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :authenticate_user_from_token!
  before_action :authenticate_user!
  before_action :check_ability!
  before_action :set_saved_anchor
  before_action :set_last_seen_at, if: proc { user_signed_in? && (session[:last_seen_at] == nil || session[:last_seen_at] < 5.minutes.ago) }
  before_action :remember_page, only: [:index, :show, :check_w, :check_q, :curves, :for_all, :configure, :import]

  private

  # source: https://gist.github.com/josevalim/fb706b1e933ef01e4fb6
  def authenticate_user_from_token!
    user_token = params['auth_token'].presence
    user       = user_token && User.where(auth_token: user_token.to_s).first #.where('auth_token_created_at > ?', (DateTime.now - 1.day)).first

    if user
      sign_in user
      params.permit!
      redirect_to url_for(params.except(:auth_token).merge(only_path: true))
    end
  end

  def after_sign_in_path_for(resource)
    #session[stored_location_key_for(resource)] || startpage_path_for(resource)
    startpage_path_for(resource)
  end

  def after_sign_out_path_for(resource_or_scope)
    root_path
  end

  def check_ability!
    # to be overridden
  end

  def set_saved_anchor
    @saved_anchor = params[:saved_anchor]
  end

  def faster_json(result)
    require 'java'
    Java::ComFasterxmlJacksonJrOb::JSON.std.asString(result)
  end

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to access_denied_path, :alert => exception.message
  end

  def parameter_editable_by_current_user?(station, parameter)
    station.editable_by?(current_user, parameter)
  end

  private

  def startpage_path_for(user)
    hinweistext = anmeldungs_hinweistext
    if hinweistext && (hinweistext != '')
      return startpage_path
    end
    if user.hat_tool_zugriff?(Tool::STAMMDATEN)
      return stammdaten_path(user)
    end
    overview_path
  end

  def stammdaten_path(user)
    unless Rails.configuration.use_new_base_data
      return "#{Service::STAMMDATEN.http_url_base}#{Service::STAMMDATEN.path_base}/startpage?auth_token=#{user.generate_token}"
    end
    stammdaten_historie_ueberblick_path(last_selected_station.id_with_namespace)
  end

  def set_last_seen_at
    current_user.update_attribute(:last_seen, Time.current)
    session[:last_seen_at] = Time.current
  end

  def anmeldungs_hinweistext
    anwendungs_konfiguration = VerwaltungContext::KonfigurationAnwendung.first
    if anwendungs_konfiguration.nil?
      return ''
    end
    unless anwendungs_konfiguration.ist_anmeldungs_hinweistext_addressat?(current_user)
      return ''
    end
    anwendungs_konfiguration.hinweistext_anmeldung || ''
  end

  def remember_page
    session[:previous_pages] ||= []
    url = url_for(params.to_unsafe_h)
    unless url.include?('/pegelfilter') || url.include?('/info_texts')
      session[:previous_pages] = [url]
    end
  end
end
