// imapd/StatusCmd.cc
// This file is part of Decimail; see http://decimail.org
// (C) 2004 -2007Philip 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 "StatusCmd.hh"

using namespace std;
using namespace pbe;


namespace Imapd {

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

    // This could be faster if we used a temporary table to store the msg_ids for the 
    // mailbox.  But it's probably only a constant-factor speedup, and who uses STATUS 
    // anyway?

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

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

    if ((attrs&messages) || (attrs&recent)) {
      SingletonQuery<int> count_messages
        (session.get_db(), "select count(*) from ("+mailbox_query+") as x");
      int msg_count = count_messages.runonce();
      if (attrs&messages) {
	response << "MESSAGES " << msg_count << " ";
      }
      if (attrs&recent) {
	response << "RECENT " << msg_count << " ";
      }
    }

    if (attrs&uidnext) {
      Query<> find_last_msgid
        (session.get_db(), mailbox_query+" order by msg_id desc limit 1");
      Result r = find_last_msgid.runonce();
      int next_uid;
      if (r.rows==1) {
	next_uid = r.get<int>(0,0)+1;
      } else {
        next_uid = session.get_db().get_next_uid()+1;  // Hmm, why +1?
      }
      response << "UIDNEXT " << next_uid << " ";
    }

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

    if (attrs&unseen) {
      SingletonQuery<int> count_unseen_messages
        (session.get_db(),
         "select count(*) from (("+mailbox_query+") "
         "where msg_id in (select msg_id u_imap_messages_flag where flag='\\Unseen')) as x");
      int unseen_msg_count = count_unseen_messages.runonce();
      response << "UNSEEN "
	       << unseen_msg_count
	       << " ";
    }

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

};
