class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :before_load_variables

  layout :layout_by_resource

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email, :password, :password_confirmation, :remember_me) }
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :name, :email, :password, :remember_me) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :password, :password_confirmation, :current_password) }
  end

  def before_load_variables
    if user_signed_in?
      @joined_projects = User.joined_projects(current_user.id)
    end
  end

  def sign_in_required
    redirect_to new_user_session_url unless user_signed_in?
  end

  def layout_by_resource
    if devise_controller?
      "auth"
    else
      "application"
    end
  end

  def method_missing(action, *args)
    if match = action.to_s.match(/^permit_project_user_by_([a-z_]{1,})/)
      permit_project_user(match[1].intern)
    else
      raise NoMethodError.new('undefined method ' + action.to_s)
    end
  end

  def permit_project_user(key)
    if params[key].nil?
      redirect_to :root
    end
    exists = ProjectMember.exists?(:project_id => params[key], :user_id => current_user.id)
    unless exists
      redirect_to :root
    end
  end

end
