//      $Id: mailbox.cpp,v 1.10 1994-12-15 18:06:18 guy Exp $

#include <stdlib.h>
#include <fstream.h>

#include <applicat.h>
#include <mailbox.h>
#include <utility.h>

#if XVT_OS == XVT_OS_DOS || XVT_OS == XVT_OS_WIN
#include <io.h>
#else
#include <unistd.h>
#endif

#define DEF_MSGS_CAPACITY 50
#define MAX_TXT_LEN 200

TMessage::TMessage(const char* to, const char* sub, 
                   const char* text, const char* from)
{
  _to = to;
  if (to && *to && (_to.len() != 6 || _to.strip(" -") != to))
    _to = cmd2name(to); 
  _subject = sub;
  _text = text;
  _from = (from == NULL || *from == '\0') ? main_app().name() : from;
  _flags = 0x00; _number = -1;
}

void TMessage::send()
{
  TMailbox mail;
  mail.send(*this);
}


void TMailbox::reread()
  // reads new messages from mailbox;
  // create messages, put messages in _msgs array in cronological order
{
  char buf[MAX_TXT_LEN];

  ifstream mbox(_path);

  // skip read messages
  mbox.seekg(_lastpos);
  while (mbox.getline(buf, MAX_TXT_LEN -1) != NULL)
  {
    // process new message
    TMessage* tmnew = new TMessage (NULL, NULL, NULL, buf);
    // lines are <from> <subject> <body>
    mbox.getline(buf, MAX_TXT_LEN -1);
    tmnew->subject(buf);
    mbox.getline(buf, MAX_TXT_LEN -1);
    tmnew->body(buf);
    _msgs.add(tmnew);
    tmnew->number(_msgs.items());
    n_new++;
  }
  _lastpos = mbox.tellg();
}

TMessage* TMailbox::next_unread()
{
  // returns next unread message;
  if (_cnt == _msgs.items())
    return NULL;
  while(this->get(_cnt)->isread())
  {
    _cnt++;
    if (_cnt == _msgs.items())
      return NULL;
  }
  n_new --;
  return this->get(_lastread = _cnt);
}

TMessage* TMailbox::next_read()
{
  // next read/unread message
  if (_cnt == _msgs.items()) 
    return NULL; 
  if (!(this->get(_cnt)->isread()))
    n_new--;
  return this->get(_cnt++);
}

TMessage* TMailbox::next(bool read)
{
  // next message, default unread
  TMessage* m = read ? next_read() : next_unread(); 
  if (m) 
    m->setread();
  return m;
}


TMessage* TMailbox::next_s(char* s, bool read)
{
  // next message with matching subject
  for (;;)
  {
    if (_cnt == _msgs.items()) 
      return NULL; 
    if (strcmp(this->get(_cnt)->subject(), s) == 0)
    {
      if (read) break;
      else
      {
        if (!(this->get(_cnt)->isread())) break;
      }
    } 
    _cnt++;
  }
  this->get(_cnt)->setread();
  if (!read) n_new--;
  return this->get(_cnt);
}

TMessage* TMailbox::next_f(char* f, bool read)
{
  // next message with matching sender
  for (;;)
  {
    if (_cnt == _msgs.items()) 
      return NULL; 
    if (strcmp(this->get(_cnt)->from(), f) == 0)
    {
      if (read) break;
      else { if (!(this->get(_cnt)->isread())) break; }
    } 
    _cnt++;
  }
  this->get(_cnt)->setread();
  if (!read) n_new--;
  return this->get(_cnt);
}

void TMailbox::send(TMessage& m)
{
  CHECK(m.from().not_empty() && m.to().not_empty() &&
        (m.subject().not_empty || m.body().not_empty()),
        "Can't send partially empty message");

  //    strcpy(to_path, getenv("TMPDIR") == NULL ? MAILDIR : getenv("TMPDIR"));
  TFilename to_path; to_path.tempdir();
  to_path << "/" << m.to() << ".mbx";

  ofstream fto(to_path, ios::app);
  CHECK(fto.good(),"send: trouble opening mailbox file");
  fto << m.from() << '\n'  << m.subject() << '\n' << m.body() << '\n';
  fto.close();
}

void TMailbox::sendcmd(int argc, char* argv[], char* to)
{
  CHECK(0,"MAILBOX::COMMANDLINE INTERFACE NOT IMPLEMENTED");
  for (int i = 0; i < argc; i++)
  {
    // parse argv[i]
    // create new message
    // send it out
  }
}

char* TMailbox::readcmd(char*)
{
  // filters all messages to recipient and adds to to_path
  CHECK(0,"MAILBOX::COMMANDLINE INTERFACE NOT IMPLEMENTED");
  // TMessage* m;
  return "NOT YET IMPLEMENTED";
}

TMailbox::TMailbox(const char* appname) : _msgs(DEF_MSGS_CAPACITY)
{
  if (appname == NULL)
    appname = main_app().name();  // myself; must be global

  _path.tempdir();
  //    strcpy(_path, getenv("TMPDIR") == NULL ? MAILDIR : getenv("TMPDIR"));
  _path << "/" << appname << ".mbx";

  _lastread =0;  _lastpos = 0l;
  n_new = 0;
  this->reread();
  restart();
}

TMailbox::~TMailbox()
{
  TMessage* m;
  // scan all remaining messages and erase mailbox
  reread();
  if (access(_path,0) == 0)
    remove(_path);
  // send unread messages to myself
  while((m = next()) != NULL)
  {
    m->to(main_app().name());
    send(*m);
  }
}