require 'ipaddr'

class Token
	include Mongoid::Document
	include Mongoid::Timestamps::Created

	index({ token: 1 })
    belongs_to :user

	field :token, type: String
	field :date_expiring, type: DateTime
	field :ip, type: Integer
    field :user_id, type: Moped::BSON::ObjectId

    ##
    # @return [Token]
	def self.authenticate(session)
		if session[:created_at].nil?
			return false
		end

		matched_token = self.where(:token				=> session[:token],
								   :ip					=> IPAddr.new(session[:ip]).to_i,
								   :date_expiring.lte	=> session[:created_at] + Rails.application.config.max_lifetime,
								   :created_at			=> session[:created_at]
				).limit(1).first

		matched_token
	end

	def save_session(session, user)
        self.token         = session[:token]
        self.date_expiring = session[:created_at] + Rails.application.config.max_lifetime
        self.created_at    = session[:created_at]
        self.ip			   = IPAddr.new(session[:ip]).to_i
        self.user_id       = user

        save
    end

	#def self.remove_old_session(token)
	#	self.delete_all(token: token)
	#end

    def self.fing_user_accounts_having_to_token(token)
        where(token: token).first().user.jids
    end

    private

	def self.generate_token
		begin
			token = SecureRandom.urlsafe_base64
		end while Token.where(token: token).exists?

		token
	end
end