import("core.project.depend")
function cmd_compile(genfile, sourcefile, template)
    print(os.programdir())
    import("find_sdk")
    local meta = find_sdk.find_my_program("refl")
    template = template or path.join(meta.sdkdir, "template/refl.liquid")
    argv = {"build", sourcefile, "-o", genfile, "-t", template}
    print("cmd_meta_compile", genfile)
    os.runv(meta.program, argv)
    return argv
end

function _listen_gen_file(target, batch, template)
    genfile, sourcefile = batch[1], batch[2]
    local dependfile = target:dependfile(genfile)
    depend.on_changed(
        function()
            cmd_compile(batch[1], batch[2], template)
        end,
        {dependfile = dependfile, files = sourcefile}
    )
end
function gen(target)
    local gen_batch = target:data("codegen.batch")
    if not gen_batch then
        return
    end
    local template = target:extraconf("rules", "c++.codegen", "template")
    for _, batch in ipairs(gen_batch) do
        if batch[2] then
            _listen_gen_file(target, batch, template)
        end
    end
end

function main(target, headerfiles)
    local sourcedir = path.join(target:autogendir({root = true}), target:plat(), "inl")
    if not os.isdir(sourcedir) then
        os.mkdir(sourcedir)
    end
    target:add("includedirs", sourcedir, {public = true})
    local gen_batch = {}
    for idx, headerfile in pairs(headerfiles) do
        -- batch
        sourcefile = path.join(sourcedir, path.basename(headerfile) .. "_gen.inl")
        table.insert(gen_batch, {sourcefile, headerfile})
    end
    -- save unit batch
    target:data_set("codegen.batch", gen_batch)
end
