module OrientDb
  module Methods
    module CountableMethods
      include OrientDb::Methods::EdgeMethods

      #it could perhaps be in the GenericMethods, if we'd like to extend to User counting.
      def get_number_of_non_visualised
        (connection.query("SELECT COUNT(*) FROM LearningObject WHERE in('Views').size() = 0"))[0]["COUNT"].to_i
      end

      def count_all
        Rails.cache.fetch('learning_object/count_all', expires_in: 6.hours) do
          result = connection.query 'SELECT COUNT(*) as count FROM LearningObject', limit: 1
          result[0]["count"]
        end
      end

      def count(edge_class, object)
        get_in_edges_count edge_class, object.id
      end

      def max(edge_class)
        Rails.cache.fetch("max_#{edge_class}", expires_in: 6.hours) do
          get_max_from_edge(edge_class, 'in')
        end
      end

      def get_max_from_edge(edge_class, type)
        max = connection.command "SELECT max(#{type}('#{edge_class}').size()) FROM LearningObject"
        max["result"][0]["max"]
      end

    end
  end
end