per_thread thread_context *ThreadLocal_ThreadContext = 0;

static thread_context AllocateThreadContext(void)
{
    thread_context Context = {};
    for(s64 ArenaIndex = 0; ArenaIndex < ArrayCount(Context.Arenas); ArenaIndex += 1)
    {
        Context.Arenas[ArenaIndex] = ArenaAllocate(Gigabytes(1));
    }
    return(Context);
}

static void SetThreadContext(thread_context *Context)
{
    ThreadLocal_ThreadContext = Context;
}

static thread_context *GetThreadContext(void)
{
    return(ThreadLocal_ThreadContext);
}

static temporary_memory GetScratch(memory_arena **Conflicts, u64 ConflictCount)
{
    temporary_memory Scratch = {};
    thread_context *Context = GetThreadContext();
    
    for(u64 ArenaIndex = 0;
        ArenaIndex < ArrayCount(Context->Arenas);
        ++ArenaIndex)
    {
        b32 FoundConflict = false;
        for(u64 ConflictIndex = 0;
            ConflictIndex < ConflictCount;
            ++ConflictIndex)
        {
            memory_arena *Conflict = Conflicts[ConflictIndex];
            if(Conflict == Context->Arenas[ArenaIndex])
            {
                FoundConflict = true;
                break;
            }
        }
        
        if(!FoundConflict)
        {
            Scratch = BeginTemporaryMemory(Context->Arenas[ArenaIndex]);
            break;
        }
    }
    
    Assert(Scratch.Arena);
    
    return(Scratch);
}
