#include "xspeakermap.h"

XSpeakerMap::XSpeakerMap()
    : XAsset()
    , mIsDefault(false)
    , mName(new XString())
    , mChannelMaps(QVector<QVector<XAudioChannelMap*>>())
{
    SetName("Speaker Map");

    for (int i = 0; i < MAP_DIM; i++)
    {
        for (int j = 0; j < MAP_DIM; j++)
        {
            mChannelMaps[i][j] = nullptr;
        }
    }
}

XSpeakerMap::~XSpeakerMap()
{
    for (int i = 0; i < mChannelMaps.size(); i++)
    {
        for (int j = 0; j < mChannelMaps[i].size(); j++)
        {
            delete mChannelMaps[i][j];
        }
    }

    delete mName;
}

QVector<QVector<XAudioChannelMap*>> XSpeakerMap::ChannelArrayToMap(const QVector<XAudioChannelMap*> aChannelArray)
{
    QVector<QVector<XAudioChannelMap*>> channelMap(MAP_DIM, QVector<XAudioChannelMap*>(MAP_DIM));

    for (int i = 0; i < MAP_DIM; i++)
    {
        for (int j = 0; j < MAP_DIM; j++)
        {
            channelMap[i][j] = aChannelArray[i * MAP_DIM + j];
        }
    }

    return channelMap;
}

void XSpeakerMap::SetIsDefault(bool aIsDefault)
{
    mIsDefault = aIsDefault;
}

bool XSpeakerMap::IsDefault() const
{
    return mIsDefault;
}

XAudioChannelMap *XSpeakerMap::GetChannelMapEntry(int aRow, int aCol)
{
    return mChannelMaps[aRow][aCol];
}

QVector<XAudioChannelMap*> XSpeakerMap::ParseChannelArray(XDataStream *aStream, int aCount)
{
    QVector<XAudioChannelMap*> result;
    for (int i = 0; i < aCount; i++)
    {
        XAudioChannelMap* newChannelMap = new XAudioChannelMap();
        newChannelMap->ParseData(aStream);
        result << newChannelMap;
    }
    return result;
}

void XSpeakerMap::ParseData(XDataStream *aStream)
{
    if (GetPtr() == -1)
    {
        *aStream >> mIsDefault;

        // Skip padding bytes in struct
        aStream->skipRawData(3);

        mName->ParsePtr(aStream, false);

        auto channelArray = ParseChannelArray(aStream, MAP_DIM);



        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                XAudioChannelMap* newChannelMap = new XAudioChannelMap();

                mChannelMaps[i][j] = newChannelMap;
            }
        }

        mName->ParseData(aStream);
    }
}

void XSpeakerMap::Clear()
{
    mIsDefault = 0;
    mName->Clear();

    for (int i = 0; i < mChannelMaps.size(); i++)
    {
        for (int j = 0; j < mChannelMaps[i].size(); j++)
        {
            delete mChannelMaps[i][j];
        }
    }
    mChannelMaps.clear();
}
