#include "xassetlist.h"
#include "qdebug.h"
#include "qfiledevice.h"

XAssetList::XAssetList()
    : XAsset()
    , mStringList()
    , mAssetCount()
    , mAssets()
    , mAssetHeaders()
    , mZoneFile(nullptr)
{
}

XAssetList::XAssetList(ZoneFile* aZoneFile)
    : XAsset()
    , mStringList()
    , mAssetCount()
    , mAssets()
    , mAssetHeaders()
    , mZoneFile(aZoneFile)
{
    SetType(ASSET_TYPE_ASSETLIST);
    SetName("Asset List");
}

XAssetList::~XAssetList()
{
    
}

void XAssetList::ParseData(QDataStream *aStream) {
    // Parse string list
    if (IsDebug())
    {
        qDebug() << QString("[%1] Parsing data for %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(GetName());
    }
    mStringList.ParsePtr(aStream);

    // Parse asset count and assets
    qint32 assetsPtr;
    *aStream
        >> mAssetCount
        >> assetsPtr;
    if (IsDebug())
    {
        qDebug() << QString("[%1] mAssetCount = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(mAssetCount);
        qDebug() << QString("[%1] assetsPtr = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(assetsPtr);
    }

    mStringList.ParseData(aStream);

    if (assetsPtr)
    {
        for (int i = 0; i < mAssetCount; i++)
        {
            XAssetHeader assetHeader(mZoneFile);
            assetHeader.ParseData(aStream);

            mAssetHeaders.append(assetHeader);
        }

        for (int i = 0; i < mAssetHeaders.size(); i++)
        {
            XAssetHeader assetHeader = mAssetHeaders[i];
            XAsset* asset = XAsset::Create(assetHeader.GetAssetType());
            asset->ParseData(aStream);

            mAssets.append(asset);
        }
    }
}

void XAssetList::Clear()
{
    
}

XScriptStringList XAssetList::GetStringList() const {
    return mStringList;
}

void XAssetList::SetStringList(const XScriptStringList& stringList) {
    mStringList = stringList;
}

QVector<XAsset*> XAssetList::GetAssets() const {
    return mAssets;
}

XAsset *XAssetList::GetAsset(size_t aIndex) const
{
    return mAssets[aIndex];
}

QVector<XAsset*> XAssetList::GetAssetsByType(XAssetType aAssetType) const
{
    QVector<XAsset *> foundAssets;
    for (int i = 0; i < mAssets.size(); i++)
    {
        XAsset* asset = mAssets[i];
        if (asset->GetType() == aAssetType)
        {
            foundAssets.append(asset);
        }
    }
    return foundAssets;
}

void XAssetList::SetAssets(QVector<XAsset *> assets) {
    mAssets = assets;
}

void XAssetList::AddAsset(XAsset *aAsset)
{
    mAssets.append(aAsset);
}

size_t XAssetList::Size() const
{
    return mAssets.size();
}
