// common/tspartindex.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 "Message.hh"
#include "Iconver.hh"

#include <iostream>

using namespace std;
using namespace pbe;


void tspartindex(DmDatabase& db, const Message& msg)
{
  const int max_length(32768);

  Query<DmDatabase::msg_id_t, string, string> insert_tsearch_part
    (db, "insert into part_tsearch (msg_id, part, data_tsidx) values "
         "($1,$2,to_tsvector('default',$3))");

  try {
    ostringstream messagedata;
    string partname;
    const mimetic::MimeEntity& me = msg.get_mimeentity();
    mimetic::ContentType ct;
    if (me.body().parts().empty()) {
      partname="BODY";
      messagedata << me.body();
      ct = me.header().contentType();
    } else {
      partname="1";
      const mimetic::MimeEntity& part1(**(me.body().parts().begin()));
      messagedata << part1.body();
      ct = part1.header().contentType();
    }

    string s = messagedata.str();

    string charset = "ISO-8859-1";
    for(mimetic::ContentType::ParamList::const_iterator i=ct.paramList().begin();
        i!=ct.paramList().end(); ++i) {
      if (i->name()=="charset") {
        charset = i->value();
      }
    }

    Iconver conv(charset,"UTF-8");
    string c;
    int l = max_length;
    while (l) {
      try {
        c = conv(s.substr(0,l));
      }
      catch (Iconver::IncompleteInput& E) {
        --l;
        continue;
      }
      break;
    }

    insert_tsearch_part(msg.get_id(),partname,c);
  }
  catch(Iconver::InvalidInput& E) {
    return;
  }
  catch(Iconver::InvalidCharset& E) {
    return;
  }
}

