# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

from ...utils.dev import log_exception
from ...utils.io import decode_json
from ...properties import Properties

from ...registries.textures.types import RepositoryType
from ...registries.texture_registry import TextureRegistry


def load_node_info(tree_name: str, type: str, index: int, tag: str):
    """
    Used to interpret the string packed to each editable node created by SNW.
    """
    props, repository_type = None, RepositoryType.Gray
    if type == 'P':
        repository_type = RepositoryType.PBR
        props = Properties.get().pbr_edit(index)
    elif type == 'G':
        repository_type = RepositoryType.Gray
        props = Properties.get().grunge_edit(index)
    elif type == 'T':
        repository_type = RepositoryType.Image
        props = Properties.get().image_edit(index)

    info = decode_json(tag)

    category, preview = '', ''

    # Try bin hash first.
    if 'bin_hash' in info:
        category, preview = TextureRegistry.instance().get_by_bin_hash(info['bin_hash'])
    if not category or not preview:
        try:
            category = info['category']
            if type == 'P':
                preview = info['pbr']
            elif type == 'G':
                preview = info['grunge']
            elif type == 'T':
                preview = info['image']
        except Exception as e:
            log_exception(e, context_msg="Failed to load node info")
    entry = TextureRegistry.instance().get_image(repository_type, category, preview)

    # Set init, so self update is prevented during init.
    props.init = True
    props.current_tree = tree_name
    try:
        props.categories = category
    except: pass # No error

    try:
        props.previews = preview
    except: pass # No error

    props.mapping = info.get('mapping', 'UV')
    props.blend = info.get('blend', 0.5)
    props.interpolation = info.get('interpolation', 'Linear')
    props.bevel_samples = info.get('bevel_samples', 0)
    props.anti_repeat_style = info.get('anti_repeat_style', 'OFF')
    props.anti_repeat_scale = info.get('anti_repeat_scale', 2.0)
    props.anti_repeat_distortion = info.get('anti_repeat_distortion', 2.0)
    props.anti_repeat_style_param_0 = info.get('anti_repeat_style_param_0', 2.0)
    props.anti_repeat_seed = info.get('anti_repeat_seed', 2.0)

    if entry and repository_type == RepositoryType.PBR:
        if  hasattr(props, 'variants'):
            variant_id = info.get('variant', 0)
            if variant_id < entry.variant_count():
                props.variants = entry.variants()[variant_id]

        if hasattr(props, 'depth_mode'):
            props.depth_mode = info.get('depth_mode', 'NONE')
            props.pom_levels = str(info.get('pom_levels', '8'))
            props.pom_fine_levels = str(info.get('pom_fine_levels', '4'))

        if hasattr(props, 'invert_normal'):
            props.invert_normal = info.get('invert_normal', False)

    props.init = False
