#include "ScriptData.h"
#include "Tool/Tool_String.h"
#include "Asset/Asset_Script.h"

ScriptData::ScriptData()
{
}

ScriptData::~ScriptData()
{

}

void ScriptData::Init(std::vector<BYTE> Data, std::string FilePath)
{
    std::string ASA = "";
    for (size_t i = 0; i < Data.size(); i++)
    {
        ASA += std::to_string((int)Data[i]);
        ASA += ",";
    }

    if (Data.size() < 7)
        return;
    IO = std::make_shared<Blob>(Data);
    filepath = FilePath;
    filetype = Tool_toLowerCase(FilePath.substr(0, FilePath.find_first_of("/")));
    filesize = Data.size();
}

std::string ScriptData::Get()
{
    if (!IO)
        return "";
    if (_CurI < filesize && filesize - _CurI >= 5)
    {
        std::string Ret = UnpackData();
        _CurI += 5;
        return Ret;
    }
    return "_nop_";
}

void ScriptData::Back()
{
    if (_CurI >= 5)
        _CurI -= 5;
}

bool ScriptData::IsEnd()
{
    return (_CurI >= filesize || filesize - _CurI < 5);
}

std::string ScriptData::UnpackData()
{
    IO->setOffset(_CurI);
    int currentByte = (int)(IO->getByte());
    int after = IO->getInt();
    switch (currentByte)
    {
    case 9:
    {
        BYTE NewcurrentByte = IO->getByte(); // 内容指示位
        (void)NewcurrentByte;
        int Newafter = IO->getInt();
        std::string Buf = Asset_Script::GetInstance().GetBinString(Newafter);
        if (Buf.empty())
            Buf = "";
        else
            Buf = Asset_Script::GetInstance().GetLoadString(filetype, Buf);
        return Buf;
    }
    case 10:
    {
        std::string Buf = Asset_Script::GetInstance().GetBinString(after);
        if (Buf.empty())
            Buf = "";
        else
            Buf = Asset_Script::GetInstance().GetLoadString(filetype, Buf);
        return Buf;
    }
    case 2:
    {
        IO->setOffset(IO->getOffset() - 4);
        int ret = IO->getInt();
        return std::to_string(ret);
    }
    case 4:
    {
        float Bbuf;
        std::memcpy(&Bbuf, &after, sizeof(float));
        return std::to_string(Bbuf);
    }
    case 6:
    case 8:
    case 7:
    case 5:
    {
        return Asset_Script::GetInstance().GetBinString(after);
    }
    default:
        return "";
    }
}
