// common/MessageFile.cc
// This file is part of Decimail; see http://decimail.org
// (C) 2004 Philip Endecott
 
// This is version $Name$
//   (if there is no version (e.g. V0-1) mentioned in the previous line,
//    this is probably a snapshot from between "official" releases.)
 
// 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 "MessageFile.hh"

#include "Recoder.hh"


MessageFile::MessageFile(string fn, int id):
  Message(id)
{
  message_file.exceptions(ifstream::failbit | ifstream::badbit);
  message_file.open(fn.c_str());
}


void MessageFile::obtain_size(void) const
{
  if (!size_valid) {
    if (entire_message_valid) {
      size=entire_message.size();
    } else {
      streampos current_pos = message_file.tellg();
      message_file.seekg(0,ios::end);
      size=message_file.tellg();
      message_file.seekg(current_pos);
    }
    size_valid=true;
  }
}


void MessageFile::obtain_entire_message(void) const
{
  if (!entire_message_valid) {
    unsigned int read_this_time;
    do {
      const int block_size=1024;
      char buf[block_size];
      read_this_time=message_file.readsome(buf,block_size);
      entire_message.append(buf,read_this_time);
    } while(read_this_time>0 && message_file.good());
    entire_message_valid=true;
  }
}


void MessageFile::find_blank_line(void) const
{
  if (!blank_line_pos_valid) {
    if (entire_message_valid) {
      blank_line_pos=entire_message.find("\n\n");
    } else {
      unsigned int searched_so_far=0;
      unsigned int read_this_time;
      do {
	const int block_size=1024;
	char buf[block_size];
	read_this_time=message_file.readsome(buf,block_size);
	entire_message.append(buf,read_this_time);
	blank_line_pos=entire_message.find("\r\n\r\n",searched_so_far);
	searched_so_far=entire_message.size();
      } while(blank_line_pos==entire_message.npos
	      && read_this_time>0 && !message_file.eof());
    }
    if (blank_line_pos==entire_message.npos) {
      throw MalformedMessage("No blank line to distinguish headers from body");
    }
    blank_line_pos_valid=true;
  }
}
