#include "xmaterialpass.h"
#include "xmaterialvertexdeclaration.h"
#include "xmaterialvertexshader.h"
#include "xmaterialpixelshader.h"

#include <QDebug>
#include <QIODevice>

XMaterialPass::XMaterialPass()
    : XAsset()
    , mVertexDecl()
    , mVertexShaderArray(15)
    , mVertexShader()
    , mPixelShader()
    , mPerPrimArgCount(0)
    , mPerObjArgCount(0)
    , mStableArgCount(0)
    , mCustomSamplerFlags(0)
    , mPrecompiledIndex(0)
    , mArgs()
{
    SetName("Material Pass");
}

void XMaterialPass::Clear()
{
    
}

void XMaterialPass::ParseData(XDataStream *aStream)
{
    if (IsDebug())
    {
        qDebug() << QString("[%1] Parsing data for %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(GetName());
    }

    mVertexDecl.ParsePtr(aStream, false);
    for (int i = 0; i < 15; i++)
    {
        mVertexShaderArray[i].ParsePtr(aStream, false);
    }
    mVertexShader.ParsePtr(aStream, false);
    mPixelShader.ParsePtr(aStream, false);

    qint32 argsPtr;
    *aStream
        >> mPerPrimArgCount
        >> mPerObjArgCount
        >> mStableArgCount
        >> mCustomSamplerFlags
        >> mPrecompiledIndex;

    aStream->skipRawData(3);

    *aStream >> argsPtr;

    if (IsDebug())
    {
        qDebug() << QString("[%1] mPerPrimArgCount = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(mPerPrimArgCount);
        qDebug() << QString("[%1] mPerObjArgCount = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(mPerObjArgCount);
        qDebug() << QString("[%1] mStableArgCount = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(mStableArgCount);
        qDebug() << QString("[%1] mCustomSamplerFlags = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(mCustomSamplerFlags);
        qDebug() << QString("[%1] mPrecompiledIndex = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(mPrecompiledIndex);
        qDebug() << QString("[%1] argsPtr = %2").arg(aStream->device()->pos(), 10, 10, QChar('0')).arg(argsPtr);
    }

    mVertexDecl.ParseData(aStream);

    for (int i = 0; i < 15; i++)
    {
        mVertexShaderArray[i].ParseData(aStream);
    }
    mVertexShader.ParseData(aStream);
    mPixelShader.ParseData(aStream);

    if (argsPtr)
    {
        int argCount = mStableArgCount + mPerObjArgCount + mPerPrimArgCount;
        for (int i = 0; i < argCount; i++)
        {
            XMaterialShaderArgument arg;
            arg.ParseData(aStream);
            mArgs.append(arg);
        }
    }
}
