class ApplicationController < ActionController::Base

	before_filter :require_login

	def require_login
		if authenticated?
			create_new_authentication()

            unless controller_name == 'chat'
                redirect_to chat_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(user_credentials = nil)
        if @token
            user_id = @token.user_id
            @token.delete
        else
            user_id = nil
        end

        @token = Token.new

        save_session(user_id, user_credentials)
    end

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

        if user_credentials
            session[:users] = {} unless session[:users]
            session[:users][user_credentials[:jid]] = user_credentials[:password]
        end

        @token.save_session(session, user_id)
    end

    def create_new_user(user_credentials)
        jid  = user_credentials[:jid]
        user = User.existing_jid(jid) || User.create_jid(jid)

        user.id
    end
end