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

from .simple import setup_gray_texture
from ...utils.dev import dbg
from ...utils.node_builder_cycles import NodeBuilderCycles
from ...registries.texture_registry import RepositoryType, TextureRegistry
from ...registries.textures.builders.gray_builder import build_gray_node_setup
from ...snw.node_info import encode_grunge_info


def _enable_uv_offset(nb: NodeBuilderCycles):
    name = 'UV Offset'
    if not nb.tree_has_input(name):
        nb.add_inputs([ ( 'Vector', name ), ], after=[ 'UV' ]) 


def create_grunge(name: str, add_uv: bool, default_bump=0.2, max_bump=20.0) -> NodeBuilderCycles:
    """
    Create an empty grunge node.
    """
    nb = NodeBuilderCycles()
    nb.build_node_tree(name)

    if add_uv:
        nb.add_inputs(
            [
                ( 'Vector' , 'UV' ),
                ( 'Vector', 'UV Offset' ),

                ( 'Float' , 'Scale', 1.0 ),
            ],
            hidden={ 'UV' }
        )

    nb.add_inputs(
        [
            ( 'FloatFactor', 'From Min', 0.0, 0.0, 1.0 ),
            ( 'FloatFactor', 'From Max', 1.0, 0.0, 1.0 ),
            ( 'FloatFactor', 'To Min', 0.0, 0.0, 1.0 ),
            ( 'FloatFactor', 'To Max', 1.0, 0.0, 1.0 ),
            ( 'FloatFactor', 'Weight', 0.0, -8.0, 8.0 ),
            ( 'FloatFactor', 'Bump Strength', default_bump, 0.0, max_bump ),
            ( 'FloatFactor', 'Bump Detail', 1.0, 0.05, 8.0 ),
            ( 'FloatFactor', 'Bump Weight', 0.0, -8.0, 8.0 ),
            ( 'FloatFactor', 'Bump From Min', 0.0, 0.0, 1.0 ),
            ( 'FloatFactor', 'Bump From Max', 1.0, 0.0, 1.0 ),
            ( 'FloatFactor', 'Blend Normal Weight', 0.0, 0.0, 1.0 ),
            ( 'Vector', 'Blend Normal', (0.0, 0.0, 1.0) ),
        ],
        hidden={ 'Blend Normal' }
    )

    nb.add_outputs([
        ( 'Float' , 'Value' ),
        ( 'Vector', 'Normal' ),
    ])

    return nb


def setup_grunge(
    nb: NodeBuilderCycles,
    category: str,
    gray: str,
    bin_hash: str = '', 
    mapping: str = 'UV',
    blend: float = 0.5,
    interpolation: str = 'Linear',
    anti_repeat_style: str = 'OFF',
    anti_repeat_scale: float = 2,
    anti_repeat_distortion: float = 0.1,
    anti_repeat_style_param_0: float = 0.1,
    anti_repeat_seed: float = 0,
    bevel_samples: int = 4,
    ):
    """
    Full a (newly created or previously cleared) grunge node with content.
    """

    dbg(f'Update Grunge: {category}/{gray} with {mapping}/{interpolation}')
    image = TextureRegistry.instance().get_image(RepositoryType.Gray, category, gray)

    nb.tree.name = image.name
    nb.tree.snw_node_info = encode_grunge_info(
        '', 
        category, 
        gray, 
        bin_hash, 
        mapping,
        blend,
        interpolation, 
        anti_repeat_style,
        anti_repeat_scale,
        anti_repeat_distortion,
        anti_repeat_style_param_0,
        anti_repeat_seed,
        bevel_samples
    )


    if mapping == 'UV':
        uv = nb.add_auto_uv(nb.input('UV'), nb.input('Scale'))
    elif mapping == 'LBOX':
        uv = nb.add_local_box_uv_mapping(nb.input('Scale'))
    elif mapping == 'GENBOX':
        uv = nb.add_generate_box_uv_mapping(nb.input('Scale'))        
    elif mapping == 'GBOX':
        uv = nb.add_global_box_uv_mapping(nb.input('Scale'))
    else:
        raise Exception('Unknown UV Mapping')
    
    _enable_uv_offset(nb) # For older nodes.
    uv = nb.add_vector_math_add(uv, nb.input('UV Offset'))    

    if anti_repeat_style != 'OFF':
        uv = nb.add_uv_anti_repeat(
            uv,
            anti_repeat_style,
            anti_repeat_scale,
            anti_repeat_distortion,
            anti_repeat_style_param_0,
            anti_repeat_seed
        )        

    proj = 'FLAT' if mapping == 'UV' else 'BOX'

    gray_socket, image = build_gray_node_setup(nb, image.info.gray, uv, proj, blend, interpolation)
    setup_gray_texture(nb, gray_socket, image.size, bevel_samples)
    