#include "xstring.h"

#include <QDebug>
#include <QIODevice>

XString::XString()
    : XAsset()
    , mString("")
    , mRemoveString("")
    , mContentLength(-1)
{
    SetName("String");
}

XString::XString(const QString aString)
    : XAsset()
    , mString(aString)
    , mRemoveString("")
    , mContentLength(-1)
{

}

XString::~XString()
{

}

QString XString::GetString() const
{
    return mString;
}

void XString::SetRemoveString(const QString aRemoveString)
{
    mRemoveString = aRemoveString;
}

void XString::SetContentLength(int aContentLength)
{
    mContentLength = aContentLength;
}

void XString::SetString(const QString& aString)
{
    mString = aString;
}

QString XString::ParseCustom(QDataStream *aStream)
{
    QString result;
    char currentChar;

    *aStream >> currentChar;
    while (currentChar != '\0')
    {
        result += currentChar;

        *aStream >> currentChar;
    }
    return result;
}

XStringArray* XString::ParseArray(QDataStream *aStream, int aCount)
{
    XStringArray* result = new XStringArray();

    for (int i = 0; i < aCount; i++)
    {
        XString* string = new XString();
        string->ParseCustom(aStream);

        result->append(string);
    }

    return result;
}

void XString::Clear()
{
    mString = "";
}

void XString::ParseData(QDataStream *aStream)
{
    if (GetPtr() == -1)
    {
        if (mContentLength == -1)
        {
            mString = ParseCustom(aStream);
        }
        else if (mContentLength != 0)
        {
            QByteArray rawString(mContentLength, Qt::Uninitialized);
            aStream->readRawData(rawString.data(), mContentLength);
            mString = QString::fromUtf8(rawString);
        }

        if (!mRemoveString.isEmpty())
        {
            mString = mString.replace(mRemoveString, "");
        }

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