require 'netaddr'

module JamWebsockets
  class TrustCheck

    attr_accessor :match, :port

    def initialize(port = 0, cidr = '0.0.0.0/0')

      @match = []
      @port = port

      if cidr.kind_of?(Array)
        cidr.each do |c|
          @match << NetAddr::CIDR.create(c)
        end
      else
        @match << NetAddr::CIDR.create(cidr)
      end
    end

    def trusted? (remote_ip, port)
      trusted = false
      if @port == 0 || port == @port
        @match.each do |cidr|
          if cidr.matches?(remote_ip)
            trusted = true
            break
          end
        end
      end
      trusted
    end
  end
end
