
import argparse
import sys
import json
from pathlib import Path
import bpy

from asset_library import constants
from asset_library.core.bl_utils import load_datablocks


def publish_asset(data_type, name):
    bpy.app.use_userpref_skip_save_on_exit = True

    blend_file = bpy.data.filepath
    preview_blend = constants.RESOURCES_DIR / 'asset_preview.blend'
    col = load_datablocks(preview_blend, names='Preview', type='collections', link=False)
    bpy.context.scene.collection.children.link(col)

    if data_type == 'node_groups':
        ntree = bpy.data.node_groups[name]
        mod = bpy.data.objects['Cube'].modifiers.new(ntree_name, 'NODES')
        mod.node_group = ntree

    bpy.context.preferences.filepaths.save_version = 0
    bpy.ops.wm.save_mainfile(compress=True, exit=True)
    #bpy.ops.wm.quit_blender()


if __name__ == '__main__' :
    parser = argparse.ArgumentParser(description='build_collection_blends',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--data-type')
    parser.add_argument('--datablock')

    if '--' in sys.argv :
        index = sys.argv.index('--')
        sys.argv = [sys.argv[index-1], *sys.argv[index+1:]]

    args = parser.parse_args()
    publish_asset(**vars(args))