// -*- C++ -*-
#include <ept/test.h>
#include <ept/core/list.h>
#include <ept/core/xapian.h>

// TODO temporary, for building test database
#include <ept/apt/apt.h>
#include <ept/textsearch/textsearch.h>
#include <ept/textsearch/maint/path.h>

using namespace ept;
using namespace core;

namespace ept {
namespace textsearch {
extern size_t max_index;
}
}

struct XapianTestEnvironment : AptTestEnvironment {
    textsearch::Path::OverrideIndexDir oid;
    textsearch::TextSearch textsearch;
    apt::Apt apt;
    XapianTestEnvironment()
        : oid( TEST_ENV_DIR "xapian" )
    {
        ept::textsearch::max_index = 1000;
        textsearch.rebuildIfNeeded(apt);
    }
};

struct TestXapian : XapianTestEnvironment {
    xapian::Source xap;
    xapian::Query query;

    TestXapian() : query( xap.db() )
    {
        query = xap.query( "sgml tool" );
    }

    Test enquire() {
        query.updateEnquire();
	Xapian::MSet matches = query.m_enq.get_mset(0, 100);
        assert( matches.size() > 0 );
        assert_eq( matches.begin().get_document().get_data(), "psgml" );
    }

    Test listCount() {
        xapian::List l( query.results() );
	Xapian::MSet matches = query.m_enq.get_mset(0, 6000);
        assert_eq( list::count( l ), matches.size() );
    }

    template< typename List >
    void checkXapianList( List l, Xapian::MSet m ) {
        Xapian::MSet::const_iterator i = m.begin();
        while (! l.empty() ) {
            assert_eq( l.token().package(), i.get_document().get_data() );
            l = l.tail();
            ++ i;
        }
    }

    Test list() {
        xapian::List l( query.results() );
	Xapian::MSet matches = query.m_enq.get_mset(0, 6000);
        checkXapianList( l, matches );
    }

    Test checkQuery() {
        assert_eq( xap.query( "sgml tool" ).results().token().package(), "psgml" );
    }

};
