#include "Core/Thread/ThreadChecker.h"

#include <Windows.h>

#include <codecvt>
#include <locale>
#include "Core/Core.h"


ThreadChecker::ThreadChecker(void) {
    std::lock_guard<std::mutex> lock(mutex_);
    if (std::thread::id() == threadId_) {
        threadId_ = std::this_thread::get_id();
    }
}

ThreadChecker::~ThreadChecker(void) {

}

bool ThreadChecker::CalledOnValideThread(void) const {
    std::lock_guard<std::mutex> lock(mutex_);
    return threadId_ == std::this_thread::get_id();
}

void ThreadChecker::DetachFromThread(void) {
    std::lock_guard<std::mutex> lock(mutex_);
    threadId_ = std::thread::id();
}

void SetThreadName(const std::string& name) {
    unsigned long threadId = ::GetCurrentThreadId();
    INFOLOG("threadname({}) -> threadid({})", name, threadId);
    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
    std::wstring threadName = converter.from_bytes(name);
    HRESULT hr = SetThreadDescription(GetCurrentThread(), threadName.c_str());
    if (FAILED(hr)) {
        ERRORLOG("SetThreadDescription failed hr={}", hr);
    }

}
