module ecs_utils.gfx.config;

import bindbc.sdl;

import ecs.std;

import ecs_utils.gfx.material;
import ecs_utils.gfx.mesh;
import ecs_utils.gfx.texture;

//import mutils.serializer.json;

extern(C):

enum LayerType
{
    normal,
    sorted
}

import ecs.vector;

static struct GfxConfig
{
    extern(C):
    __gshared:
    Vector!LayerType layers;
    //Vector!Mesh meshes;
    //Vector!Material materials;
    Mesh[] meshes;
    Material[] materials;

    static bool load(const (char)[] path) nothrow
    {
        struct LoadData
        {
            struct Str
            {
                @("malloc") string str;
            }

            @("malloc") Str[] materials;
            @("malloc") Str[] meshes;
            int inter;

            void dispose() nothrow
            {
                /*if(blend_mode)Mallocator.instance.dispose(cast(char[])blend_mode);
                if(vertex)Mallocator.instance.dispose(cast(char[])vertex);
                if(fragment)Mallocator.instance.dispose(cast(char[])fragment);*/
            }
        }

        char[] cpath = (cast(char*)alloca(path.length+1))[0..path.length+1];
        cpath[0..$-1] = path[0..$];
        cpath[$-1] = 0;

        SDL_RWops* file = SDL_RWFromFile(cpath.ptr,"r");
        if(file)
        {
            size_t size = cast(size_t)SDL_RWsize(file);
            char[] buffer = Mallocator.makeArray!char(size);
            SDL_RWread(file,buffer.ptr,size,1);

            LoadData load_data;
            scope(exit)load_data.dispose();

            /*JSONSerializer serializer = Mallocator.make!JSONSerializer;
            scope(exit)Mallocator.dispose(serializer);
            serializer.serialize!(Load.yes, true)(load_data,buffer);*/

            //if(__ecs_used_backend == Backend.opengl)
            {
                meshes = Mallocator.makeArray!Mesh(load_data.meshes.length);
                foreach(i,ref mesh; meshes)
                {
                    mesh.load(load_data.meshes[i].str);
                    mesh.uploadData();
                }
            }
            
            materials = Mallocator.makeArray!Material(load_data.materials.length);
            foreach(i,ref material; materials)
            {
                material.create();
                material.load(load_data.materials[i].str);
                material.compile();
            }

            SDL_RWclose(file);
            load_data.dispose();
            return true;
        }
        else return false;
    }

    static int addLayer(LayerType type)
    {
        layers.add(type);
        return cast(int)(layers.length-1);
    }
}