var query = require('./query')
var select = require('./select')

var pull = require('pull-stream')
var isArray = Array.isArray

var u = require('./util')

module.exports = function (indexes, scan) {
  return function explain (opts) {
    opts = opts || {}
    var q, k, sort

    if(isArray(opts.query)) {
      q = opts.query[0].$filter || {}
      sort = opts.query[opts.query.length-1].$sort
    }
    else if(opts.query) {
      q = opts.query
    }
    else
      q = {}

    var index = sort && u.findByPath(indexes, sort) || select(indexes, q)

    if(!index) return {
      scan: true,
      createStream: scan,
      reverse: !!opts.reverse,
      live: !!(opts.live === true || opts.old === false),
      old: opts.old !== false,
      sync: !!opts.sync
    }

    var _opts = query(index, q, index.exact)
    _opts.reverse = !!opts.reverse
    //same default logic as pull-live
    _opts.old = (opts.old !== false)
    _opts.live = (opts.live === true || opts.old === false)
    _opts.createStream = index.createStream
    //TODO test coverage for live/old
    _opts.sync = opts.sync
    return _opts
  }
}



@@ -478,21 +478,17 @@
     var 
-index
+r
  = sort 
@@ -489,16 +489,24 @@
  sort &&
+ %7Bindex:
  u.findB
@@ -525,16 +525,29 @@
 s, sort)
+, scores: %7B%7D%7D
  %7C%7C sele
@@ -559,18 +559,47 @@
 dexes, q
-)%0A
+, true)%0A    var index = r.index
 %0A    if(
@@ -798,24 +798,106 @@
  !!opts.sync
+,%0A      //also return the name of the index and the scores for indexes considered!
 %0A    %7D%0A%0A    
@@ -1216,16 +1216,73 @@
 ts.sync%0A
+    _opts.index = index.key,%0A    _opts.scores = r.scores%0A
     retu
@@ -1298,8 +1298,7 @@
   %7D%0A
+
 %7D%0A%0A
-%0A

return index name and scores