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

from asset_library import constants
from asset_library.core.bl_utils import load_datablocks
from asset_library.core.lib_utils import clear_time_tag, create_time_tag, version_file
from asset_library.core.catalog import Catalog


def get_all_datablocks():
    blend_datas = [
        bpy.data.collections, bpy.data.objects, 
        bpy.data.materials, bpy.data.node_groups, bpy.data.worlds]
    
    return [o for blend_data in blend_datas for o in blend_data]


def publish_library_assets(library, assets, catalogs):
    bpy.app.use_userpref_skip_save_on_exit = True
    bpy.context.preferences.filepaths.save_version = 0

    for asset, catalog_path in zip(assets, catalogs):
        asset_path, asset_type, asset_name = asset.rsplit('/', 2)

        #print(asset_path, asset_type, asset_name)

        asset = load_datablocks(asset_path, names=asset_name, type=asset_type, link=False)

        if not asset.asset_data:
            asset.asset_mark()
        
        # clear asset_mark of all other assets
        for datablock in get_all_datablocks():
            if datablock != asset and datablock.asset_data:
                datablock.asset_clear()

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

        elif asset_type == 'objects':
            bpy.data.objects.remove(bpy.data.objects['Cube'])
            bpy.data.collections['Preview'].objects.link(asset)
        
        elif asset_type == 'materials':
            bpy.data.objects['Cube'].data.materials.append(asset)

        #catalog_path = asset.asset_data.catalog_simple_name.replace('-', '/')
        asset_publish_path = Path(library, catalog_path, asset.name).with_suffix('.blend')
        asset_publish_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Assign or Create catalog
        catalog = Catalog(library)
        catalog.read()

        if catalog_item := catalog.get(path=catalog_path):
            catalog_id = catalog_item.id
        else:
            catalog_id = catalog.add(catalog_path).id
            catalog.write()
        
        asset.asset_data.catalog_id = catalog_id

        # Created time tag
        clear_time_tag(asset)
        create_time_tag(asset)

        version_file(asset_publish_path)

        bpy.ops.object.make_local(type='ALL')
        bpy.ops.file.make_paths_relative()
        bpy.ops.wm.save_as_mainfile(filepath=str(asset_publish_path), compress=True, copy=True, relative_remap=True)
        bpy.ops.wm.revert_mainfile()

    bpy.ops.wm.quit_blender()


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

    parser.add_argument('--library')
    parser.add_argument('--assets', nargs='+')
    parser.add_argument('--catalogs', nargs='+')

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

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