#include "GameState.h"
#include "SquirrelActor.h"

extern SquirrelClassEx* TObject;
extern NPK_M* npk;
std::map<std::string, Sound*>SoundRecObject;
std::unordered_map<std::string, std::map<int,TexturePtr>>ImageRecObject;
std::map<std::string, FontPtr>FontRecObject;
WThreadPool threadPool;
Cursor* Mouse_Object = new Cursor();

void InitSound(const TCHAR* directory)
{
    WIN32_FIND_DATA fileInfo;
    TCHAR buffer[MAX_PATH];

    // 构建搜索路径
    _tcscpy_s(buffer, directory);
    _tcscat_s(buffer, _T("\\*.*"));

    // 查找第一个文件/目录
    HANDLE hFind = FindFirstFile(buffer, &fileInfo);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            // 排除 "." 和 ".."
            if (_tcscmp(fileInfo.cFileName, _T(".")) != 0 && _tcscmp(fileInfo.cFileName, _T("..")) != 0)
            {
                // 如果是目录，则递归遍历子目录
                if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                {
                    _tcscpy_s(buffer, directory);
                    _tcscat_s(buffer, _T("\\"));
                    _tcscat_s(buffer, fileInfo.cFileName);
                    InitSound(buffer);
                }
                else {
                    // 输出文件名
                    //_tprintf(_T("%s\\%s\n"), directory, fileInfo.cFileName);

                    char output[1024];
                    sprintf(output, "%ws\\%ws", directory,fileInfo.cFileName);
                    std::string path = output;
                    std::replace(path.begin(), path.end(), '\\', '/');

                    Sound* sou = new Sound(path);
                    //sou->Preload(path);
                    SoundRecObject[path] = sou;
                    //std::cout << "音频资源___" << path << "____已加载" << std::endl;
                }
            }
        } while (FindNextFile(hFind, &fileInfo));

        FindClose(hFind);
    }
}

void InitFont(const TCHAR* directory)
{
    WIN32_FIND_DATA fileInfo;
    TCHAR buffer[MAX_PATH];

    // 构建搜索路径
    _tcscpy_s(buffer, directory);
    _tcscat_s(buffer, _T("\\*.*"));

    // 查找第一个文件/目录
    HANDLE hFind = FindFirstFile(buffer, &fileInfo);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            // 排除 "." 和 ".."
            if (_tcscmp(fileInfo.cFileName, _T(".")) != 0 && _tcscmp(fileInfo.cFileName, _T("..")) != 0)
            {
                // 如果是目录，则递归遍历子目录
                if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                {
                    _tcscpy_s(buffer, directory);
                    _tcscat_s(buffer, _T("\\"));
                    _tcscat_s(buffer, fileInfo.cFileName);
                    InitFont(buffer);
                }
                else {
                    // 输出文件名
                    //_tprintf(_T("%s\\%s\n"), directory, fileInfo.cFileName);

                    char output[1024];
                    sprintf(output, "%ws\\%ws", directory, fileInfo.cFileName);
                    std::string path = output;
                    std::replace(path.begin(), path.end(), '\\', '/');

                    FontPtr FontBuf = new Font();
                    FontBuf->Preload(path);
                    FontRecObject[path] = FontBuf;
                }
            }
        } while (FindNextFile(hFind, &fileInfo));

        FindClose(hFind);
    }
}

void LoadingScene_Success()
{
    KGE_DEBUG_LOG("资源加载完成");
    Stage* P_Stage = Director::GetInstance().GetCurrentStage().Get();
    SquirrelStage* Push_Stage = (SquirrelStage*)P_Stage;
    TObject->RunSceneScript("LoadingGame_Stage_Func", Push_Stage);
}

void InitGameRecFunc() {

    //加载List
    SquirrelClassEx::LoadingListScript();
    //Sleep(4000);
    //加载音频资源
    InitSound(L"SoundPacks2/music");
    //加载字体资源
    InitFont(L"Font");

    //预加载一下选择角色那个背景不然有点卡
    for (size_t i = 0; i < 17; i++)
    {
        SquirrelClassEx::GetTexturePtrByImg("sprite/selectcharacter/background.img", i);
    }
    IMG* img = npk->ReadNpkTable("sprite/selectcharacter/background.img");
    npk->ReleaseNpkTable(img);

    Application::GetInstance().PerformInMainThread(LoadingScene_Success);

    
}



//#include <irrKlang.h>
//KGE_DECLARE_SMART_PTR(ISound);
void Setup()
{
    //线程池初始化
    threadPool.setMaxThreadNum(10);

    //打开输入法
    WindowPtr window = Application::GetInstance().GetWindow();
    window->SetImmEnabled(true);

    //New一个新线程去加载游戏所需资源
    threadPool.concurrentRun(InitGameRecFunc);

    //打开渲染模式
    Director::GetInstance().SetRenderBorderEnabled(true);

    //irrklang::ISoundEngine* engine = irrklang::createIrrKlangDevice();



    


    /*SoundPtr SP = new Sound();
    SP*/
    /*loader.Load(fileData.get(), "ogg", memory.buffer);*/

    //Renderer::GetInstance().GetContext().SetTextAntialiasMode(TextAntialiasMode::None);
}


void GameState::Run()
{
    // 游戏设置
    Settings s;
    s.window.title = "Yosin - DOF"; // 窗口标题
    s.window.width = 1600;           // 窗口宽度
    s.window.height = 900;          // 窗口高度
    // 取消垂直同步
    s.vsync_enabled = false;
    // 设置帧间隔时间
    s.frame_interval = 1_sec / 10000;
    s.debug_mode = true;

    // 开启日志系统
    //Logger::GetInstance().Enable();

    //Application::GetInstance().Use(ImGuiModule::GetInstance());
    Application::GetInstance().Use(AudioModule::GetInstance());
    // 启动应用
    Application::GetInstance().Run(s, Setup);

}
