class ApplicationController < ActionController::Base

	before_filter :require_login

	def require_login
		if authenticated?
			create_new_authentication()

            unless controller_name == 'chat'
                redirect_to chat_template_path
            end
		else
			unless controller_name == 'sessions' && (action_name == 'new' || action_name == 'create')
                redirect_to root_url, flash: {error: I18n.t('login.access-denied')}
			end
		end
	end

	protected

	def authenticated?
        @token = Token.authenticate(session)
	end

	def create_new_authentication(jid = nil)
        if @token
            user_id = @token.user_id
            @token.delete
        else
            user_id = jid.nil? ? nil : create_new_user(jid)
        end

        @token = Token.new

        save_session(user_id)
    end

    def save_session(user_id)
        session[:token] = Token.generate_token()
        session[:created_at] = Time.now
        session[:ip] = request.remote_ip

        @token.save_session(session, user_id)
    end

    def create_new_user(jid)
        user = User.new(jid: jid)
        user.id if user.save
    end
end