/*
 * libjingle
 * Copyright 2004--2005, Google Inc.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice, 
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *  3. The name of the author may not be used to endorse or promote products 
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "talk/xmpp/xmpptask.h"
#include "talk/xmpp/xmppclient.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/constants.h"

namespace buzz {

XmppTask::XmppTask(Task * parent, XmppEngine::HandlerLevel level)
 : Task(parent), client_(NULL) {
  XmppClient * client = (XmppClient*)parent->GetParent(XMPP_CLIENT_TASK_CODE);
  client_ = client;
  id_ = client->NextId();
  client->AddXmppTask(this, level);
  client->SignalDisconnected.connect(this, &XmppTask::OnDisconnect);
}

XmppTask::~XmppTask() {
  StopImpl();
}

void
XmppTask::StopImpl() {
  while (NextStanza() != NULL) {}
  if (client_) {
    client_->RemoveXmppTask(this);
    client_->SignalDisconnected.disconnect(this);
    client_ = NULL;
  }
}

XmppReturnStatus
XmppTask::SendStanza(const XmlElement * stanza) {
  if (client_ == NULL)
    return XMPP_RETURN_BADSTATE;
  return client_->SendStanza(stanza);
}

XmppReturnStatus
XmppTask::SendStanzaError(const XmlElement * element_original,
                                XmppStanzaError code,
                                const std::string & text) {
  if (client_ == NULL)
    return XMPP_RETURN_BADSTATE;
  return client_->SendStanzaError(element_original, code, text);
}

void
XmppTask::Stop() {
  StopImpl();
  Task::Stop();
}

void
XmppTask::OnDisconnect() {
  Error();
}

void
XmppTask::QueueStanza(const XmlElement * stanza) {
  stanza_queue_.push_back(new XmlElement(*stanza));
  Wake();
}

const XmlElement *
XmppTask::NextStanza() {
  XmlElement * result = NULL;
  if (!stanza_queue_.empty()) {
    result = stanza_queue_.front();
    stanza_queue_.pop_front();
  }
  next_stanza_.reset(result);
  return result;
}

XmlElement *
XmppTask::MakeIq(const std::string & type,
  const buzz::Jid & to, const std::string id) {
  XmlElement * result = new XmlElement(TQN_IQ);
  if (!type.empty())
    result->AddAttr(TQN_TYPE, type);
  if (to != JID_EMPTY)
    result->AddAttr(TQN_TO, to.Str());
  if (!id.empty())
    result->AddAttr(TQN_ID, id);
  return result;
}

XmlElement *
XmppTask::MakeIqResult(const XmlElement * query) {
  XmlElement * result = new XmlElement(TQN_IQ);
  result->AddAttr(TQN_TYPE, STR_RESULT);
  if (query->HasAttr(TQN_FROM)) {
    result->AddAttr(TQN_TO, query->Attr(TQN_FROM));
  }
  result->AddAttr(TQN_ID, query->Attr(TQN_ID));
  return result;
}

bool
XmppTask::MatchResponseIq(const XmlElement * stanza,
    const Jid & to, const std::string & id) {
  if (stanza->Name() != TQN_IQ)
    return false;

  if (stanza->Attr(TQN_ID) != id)
    return false;

  Jid from(stanza->Attr(TQN_FROM));
  if (from != to) {
    Jid me = client_->jid();
    // we address the server as "", but it is legal for the server
    // to identify itself with "domain" or "myself@domain"
    if (to != JID_EMPTY) {
      return false;
    }

    if (from != Jid(me.domain()) && from != me.BareJid()) {
      return false;
    }
  }


  return true;
}

bool
XmppTask::MatchRequestIq(const XmlElement * stanza,
    const std::string & type, const TQName & qn) {
  if (stanza->Name() != TQN_IQ)
    return false;

  if (stanza->Attr(TQN_TYPE) != type)
    return false;

  if (stanza->FirstNamed(qn) == NULL)
    return false;

  return true;
}

}
