module Runtime
  class << self

    # Return the base paths to the runtime directories.
    #
    # @return [Array] Current runtime paths.
    def paths
      @paths ||= default_paths
    end

    # Find a runtime file.
    #
    # @param type [Symbol]
    #   Type of runtime file to find. Options:
    #   - :shader
    #   - :font
    # @param name [String]
    #   Name of the runtime file to locate.
    #
    # @return [String, nil]
    #   Path to the runtime file, or +nil+ if not found.
    def find(type, name)
      path = nil
      paths.find do |runtime_path|
        path = find_in(type, name, runtime_path)
      end
      path
    end

    private

    # Return the default runtime paths.
    #
    # @return [Array] Default runtime paths.
    def default_paths
      paths = []
      user_path = File.expand_path("~/.jes")
      if File.directory?(user_path)
        paths << user_path
      end
      paths << File.expand_path("../../runtime", $0)
      paths
    end

    # Find a runtime file within a single runtime path.
    #
    # @param type [Symbol]
    #   Type of runtime file to find. Options:
    #   - :shader
    #   - :font
    # @param name [String]
    #   Name of the runtime file to locate.
    # @param runtime_path [String]
    #   The runtime path to look in.
    #
    # @return [String, nil]
    #   Path to the runtime file, or +nil+ if not found.
    def find_in(type, name, runtime_path)
      path =
        case type
        when :shader
          File.join(runtime_path, "shaders", name)
        else
          raise "Unknown runtime type: #{type.inspect}"
        end
      if File.exists?(path)
        path
      else
        nil
      end
    end

  end
end
