
/*---------------------------------------------------------------------------*/
/* http_vfs_entry.cpp                                                        */
/* copyright (c) innovaphone 2015                                            */
/*                                                                           */
/*---------------------------------------------------------------------------*/

#include "platform/platform.h"

#include "common/lib/httplib.h"

#include "common/interface/socket.h"
#include "common/interface/webserver_plugin.h"

#include "common/service/webserver_shared/webserver_internal.h"

#include "types.h"
#include "http_method_handler.h"
#include "http_connection.h"
#include "http_datasource.h"
#include "http_vfs_entry.h"


HTTPVfsEntry::HTTPVfsEntry(const char * name, HTTPVfsEntry * parent)
{
    this->name = _strdup(name);
    this->childs = nullptr;
    this->parent = parent;
    this->dataSource = nullptr;
}


HTTPVfsEntry::~HTTPVfsEntry()
{
    // Deleting childs deletes the first item in the btree. This item will call its parents RemoveChild()
    // function (so the function of this instance) to remove itself from the btree before it will be
    // deleted.
    while (childs != nullptr) delete childs;

    // Check parent for nullptr, because the root of the VFS doesn't have a parent.
    if (this->parent != nullptr) this->parent->RemoveChild(this);

    free(name);
}


int HTTPVfsEntry::btree_compare(void * key)
{
    return strcmp((char *)key, name);
}


int HTTPVfsEntry::btree_compare(class btree * b)
{
    return this->btree_compare(static_cast<HTTPVfsEntry *>(b)->name);
}


HTTPVfsEntry * HTTPVfsEntry::FindChild(const char * name)
{
    return static_cast<HTTPVfsEntry *>(this->childs->btree_find(name));
}


void HTTPVfsEntry::RemoveChild(HTTPVfsEntry * child)
{
    this->childs = static_cast<HTTPVfsEntry *>(this->childs->btree_get(child));
}


void HTTPVfsEntry::RemoveDataSourceRecursive(HTTPDataSource * dataSource)
{
    if (dataSource != nullptr) {
        if (this->dataSource == dataSource) this->dataSource = nullptr;

        HTTPVfsEntry * curChild = static_cast<HTTPVfsEntry *>(this->childs->btree_find_left());
        while (curChild != nullptr) {
            curChild->RemoveDataSourceRecursive(dataSource);
            curChild = static_cast<HTTPVfsEntry *>(this->childs->btree_find_next_left(curChild->GetName()));
        }
    }
}
