// imapd/StatusCmd.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 "StatusCmd.hh"

namespace Imapd {

  void StatusCmd::runbody(Session& session)
  {
    session.check_state(Session::auth|Session::selected);

    string mailbox_query;
    try {
      mailbox_query =
	session.get_db().get_mailbox_query(session.get_username(),mailbox_name);
    }
    catch (DmDatabase::MailboxDoesNotExist& E) {
      throw RespondNo("Mailbox does not exist");
    }

    ostringstream response;
    response << "STATUS \"" << mailbox_name << "\" (";

    if ((attrs&messages) || (attrs&recent)) {
      DmDatabase::Query q(&session.get_db());
      q << "select count(*) from ("
	<< mailbox_query
	<< ") as x;";
      q.run();
      int msg_count = q.get_num(0,0);
      if (attrs&messages) {
	response << "MESSAGES " << msg_count << " ";
      }
      if (attrs&recent) {
	response << "RECENT " << msg_count << " ";
      }
    }

    if (attrs&uidnext) {
      DmDatabase::Query q1(&session.get_db());
      q1 << mailbox_query
	 << " order by msg_id desc limit 1;";
      q1.run();
      int next_uid;
      if (q1.get_ntuples()==1) {
	next_uid = q1.get_num(0,0)+1;
      } else {
	DmDatabase::Query q2(&session.get_db());
	q2 << "select last_value from msg_ids;";
	q2.run();
	next_uid = q2.get_num(0,0)+1;
      }
      response << "UIDNEXT " << next_uid << " ";
    }

    if (attrs&uidvalidity) {
      response << "UIDVALIDITY 1 ";
    }

    if (attrs&unseen) {
      DmDatabase::Query q(&session.get_db());
      q << "select count(*) from (("
	<< mailbox_query
	<< ") intersect (select msg_id from imap_unseen_messages)) as x;";
      q.run();
      int unseen_msg_count = q.get_num(0,0);
      response << "UNSEEN "
	       << unseen_msg_count
	       << " ";
    }

    response.seekp(-1,ios_base::cur);
    response << ')';
    session.respond_untagged(response.str());
  }

};
