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

#include "utils.hh"

namespace Imapd {

  void SelectOrExamineCmd::runbody(Session& session)
  {
    session.check_state(Session::auth|Session::selected);
    try {
      session.set_mailbox(mailbox_name);
    }
    catch(DmDatabase::MailboxDoesNotExist& E) {
      session.clear_mailbox();
      session.set_state(Session::auth);
      throw RespondNo("Mailbox "+mailbox_name+" does not exist");
    }
    catch(...) {
      session.clear_mailbox();
      session.set_state(Session::auth);
      throw;
    }
    session.set_state(Session::selected);

    session.get_msg_ids();

    session.respond_untagged("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
    session.respond_untagged("OK [PERMANENTFLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)]");
    int exists = session.seqnum_to_msgid.size()-1;
    session.respond_untagged(int_to_string(exists)+" EXISTS");
    int recent = exists;
    session.respond_untagged(int_to_string(recent)+" RECENT");
    session.respond_untagged("OK [UIDVALIDITY 1]");

    DmDatabase::Query q1(&session.get_db());
    q1 << "(" << session.get_mailbox_query() << ")"
       << " intersect (select msg_id from imap_unseen_messages)"
       << " order by msg_id limit 1;";
    q1.run();
    if (q1.get_ntuples()!=0) {
      int first_unseen_msgid = q1.get_num(0,0);
      int first_unseen_seqnum = session.msgid_to_seqnum[first_unseen_msgid];
      session.respond_untagged("OK [UNSEEN "+int_to_string(first_unseen_seqnum)+"]");
    }

    int next_uid;
    if (session.seqnum_to_msgid.empty()) {
      DmDatabase::Query q2(&session.get_db());
      q2 << "select  last_value from msg_ids;";
      q2.run();
      next_uid = q2.get_num(0,0)+1;
    } else {
      next_uid = *(session.seqnum_to_msgid.end()-1) + 1;
    }
    session.respond_untagged("OK [UIDNEXT "+int_to_string(next_uid)+"]");
    
    if (readonly) {
      response_code = "[READ-ONLY] ";
    } else {
      response_code = "[READ-WRITE] ";
    }
  }

};
