#include <cassert>
#include "xf/timeout.h"
#include "xf/initialevent.h"
#include "xf/behavior.h"
#include "trace/trace.h"


XFBehavior::XFBehavior() {
    this->deleteOnTerminate_ = false;
}

XFBehavior::~XFBehavior() {
}

void XFBehavior::startBehavior() {
    GEN(XFInitialEvent());
}

void XFBehavior::pushEvent(XFEvent *pEvent) {
    if(pEvent->getBehavior()==nullptr) {
        pEvent->setBehavior(this);
    }
    this->getDispatcher()->pushEvent(pEvent);
}

bool XFBehavior::deleteOnTerminate() const {
    return this->deleteOnTerminate_;
}

void XFBehavior::setDeleteOnTerminate(bool deleteBehaviour) {
    this->deleteOnTerminate_ = deleteBehaviour;
}

const XFEvent *XFBehavior::getCurrentEvent() const {
    return this->pCurrentEvent_;
}

interface::XFDispatcher *XFBehavior::getDispatcher() {
    return interface::XFDispatcher::getInstance();
}

const XFTimeout *XFBehavior::getCurrentTimeout() {
    if(pCurrentEvent_->getEventType() == XFEvent::Timeout) {
        return (XFTimeout*) this->pCurrentEvent_;
    } else {
        return nullptr;
    }
}

void XFBehavior::setCurrentEvent(const XFEvent *pEvent) {
    this->pCurrentEvent_ = pEvent;
}

XFBehavior::TerminateBehavior XFBehavior::process(const XFEvent *pEvent) {
    this->setCurrentEvent(pEvent);
    XFEventStatus status = XFEventStatus::Unknown;
    status = this->processEvent();
    if(status == XFEventStatus::Consumed && pEvent->deleteAfterConsume()) {
        delete pEvent;
    }
    XFBehavior::TerminateBehavior terminateBehavior = false;
    if(status == XFEventStatus::Terminate) {
        terminateBehavior = true;
    }
    return terminateBehavior;
}
