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 = !user_credentials ? nil : create_new_user(user_credentials)
        end

        @token = Token.new

        save_session(user_id) if not 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(user_credentials)
        jid  = user_credentials[:jid]
        pass = user_credentials[:password]

        user = User.existing_jid(jid) || User.create_jid(jid)
        user.update_pass(jid, pass)

        user.id
    end
end