// partindexd/main.cc
// This file is part of Decimail; see http://decimail.org
// (C) 2007 Philip Endecott
 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#include "Exception.hh"
#include "DmDatabase.hh"
#include "MessageDb.hh"
#include "tspartindex.hh"

#include <iostream>

using namespace std;
using namespace pbe;


static void do_index(int max_messages)
{
  cout << "connecting to database\n";

  DmDatabase db;

  Transaction t(db);

  cout << "getting msg_ids\n";

  // This query is slow especially for large limits unless your work_mem
  // postgresql configuration setting is large enough that a hashed_subplan
  // can be used.  Hence the rather small max_messages passed from main().
  // If you are confident that a hashed subplan will be used (e.g. you have
  // checked with explain analyse) you can increase that value.
  ColumnQuery<DmDatabase::msg_id_t, int> get_unindexed_messages
    (db, "select msg_id from messages where msg_id not in (select msg_id from part_tsearch) limit $1");

  typedef ColumnResult<DmDatabase::msg_id_t> result_t;
  result_t r = get_unindexed_messages(max_messages);

  cout << "done\n";

  for(result_t::const_iterator i = r.begin();
      i != r.end(); ++i) {
    DmDatabase::msg_id_t m = *i;
    cout << "Indexing message " << m << "\n";
    MessageDb msg(db,m);
    tspartindex(db,msg);
  }
  t.commit();
}



int main(int argc, char* argv[])
{
  try { try {

    for (int i=1; i<argc; ++i) {
      string arg(argv[i]);
      DmDatabase::add_connection_string(arg);
    }

    do_index(10);

  } RETHROW_MISC_EXCEPTIONS }
  catch (Exception& E) {
    cerr << "Unhandled exception: ";
    E.report(cerr);
    exit(E.exit_status);
  }
}
