import bpy
from bpy.props import PointerProperty
from bpy.app.handlers import persistent
import os
import uuid
import bpy.utils.previews
from .ssm_functions import (
    automode_activation_instances,
    daz_import_activation,
    catch_error
)

# Details of add-on

bl_info = {
    "name"       : "SUPER Solid Mode",
    "author"     : "Toapy & Friends",
    "version"    : (5, 0, 6),
    "blender"    : (3, 3, 1),
    "location"   : "Header>TOP-RIGHT>Button w/ Sphere Icon",
    "description": "Awesome New Features for Blender!",
    "warning"    : "When uninstalling, restart Blender for changes to take effect.",
    "doc_url"    : "https://drive.google.com/file/d/1BD57ZhlOhqEc-xwxuqTgVsqB8g0viHVf/view",
    "category"   : "3D View",
    }


# DRAW FUNCTIONS
# SSM_ActivateDiffuseTexture Operator
def draw_activate_diffuse_texture(self, context):
    draw_activate_diffuse_texture.f(self, context)
    self.layout.operator("ssm.activate_diffuse_texture", text = "", icon = "RADIOBUT_ON")

draw_activate_diffuse_texture.f = bpy.types.TOPBAR_HT_upper_bar.draw_right

# Easy Animation UI
# Frame controls
def draw_ssm_frame_controls(self, context):
    manager = context.scene.super_solid_mode
    layout = self.layout

    if manager.set_frame:
        col = layout.column()
        col.operator("anim.start_frame_set", text="", icon="REW")

    if manager.skip_frames:
        col = layout.column()
        col.operator("ssm.jump_backward", text="", icon="BACK")
        col = layout.column()
        col.prop(manager, "jump_count", text="")
        col = layout.column()
        col.operator("ssm.jump_forward", text="", icon="FORWARD")

    if manager.set_frame:
        col = layout.column()
        col.operator("anim.end_frame_set", text="", icon="FF")

    col = layout.column()
    col.label(text=' ')

    if manager.to_sequencer_t:
        col = layout.column()
        col.operator("ssm.switch_to_sequencer_t", text="", icon="SEQUENCE")
        
    if manager.to_shader_editor_t:
        col = layout.column()
        col.operator("ssm.switch_to_shader_editor_t", text="", icon="NODE_MATERIAL")
        
    if manager.to_dope_sheet_t:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_dope_sheet_t', text='', icon="ACTION")   

    if manager.to_graph_editor_t:
        col = layout.column()
        col.operator("ssm.switch_to_graph_editor_t", text="", icon="GRAPH")                
        
    if manager.open_keyframe:
        col = layout.column()
        col.label(text=' ')
        col = layout.column()
        col.operator("anim.keyframe_insert_menu", text="", icon="KEYTYPE_KEYFRAME_VEC")
        
# Shader Editor        
def draw_shader_editor(self, context):
    manager = context.scene.super_solid_mode
    layout = self.layout
        
    if manager.to_timeline_se:
        col = layout.column()
        col.operator("ssm.switch_to_timeline_se", text="", icon="TIME")
        
    if manager.to_sequencer_se:
        col = layout.column()
        col.operator("ssm.switch_to_sequencer_se", text="", icon="SEQUENCE")
        
    if manager.to_dope_sheet_se:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_dope_sheet_se', text='', icon="ACTION")    
        
    if manager.to_graph_editor_se:
        col = layout.column()
        col.operator("ssm.switch_to_graph_editor_se", text="", icon="GRAPH")        
        
    if manager.frame_all:
        col = layout.column()
        col.label(text=' ')
        col = layout.column()
        col.operator('ssm.frame_all', text='', icon='VIEWZOOM')
        
# Dope Sheet        
def draw_dope_sheet(self, context):
    manager = context.scene.super_solid_mode
    layout = self.layout
        
    if manager.to_timeline_ds:
        col = layout.column()
        col.operator("ssm.switch_to_timeline_ds", text="", icon="TIME")
        
    if manager.to_sequencer_ds:
        col = layout.column()
        col.operator("ssm.switch_to_sequencer_ds", text="", icon="SEQUENCE")
        
    if manager.to_shader_editor_ds:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_shader_editor_ds', text='', icon="NODE_MATERIAL")    
        
    if manager.to_graph_editor_ds:
        col = layout.column()
        col.operator("ssm.switch_to_graph_editor_ds", text="", icon="GRAPH")  
        
# Graph Editor        
def draw_graph_editor(self, context):
    manager = context.scene.super_solid_mode
    layout = self.layout
        
    if manager.to_timeline_ge:
        col = layout.column()
        col.operator("ssm.switch_to_timeline_ge", text="", icon="TIME")
        
    if manager.to_sequencer_ge:
        col = layout.column()
        col.operator("ssm.switch_to_sequencer_ge", text="", icon="SEQUENCE")
        
    if manager.to_shader_editor_ge:
        col = layout.column()
        col.operator("ssm.switch_to_shader_editor_ge", text="", icon="NODE_MATERIAL")
        
    if manager.to_dope_sheet_ge:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_dope_sheet_ge', text='', icon="ACTION")        
    
    
# TOPBAR       
def draw_topbar(self, context):
    manager = context.scene.super_solid_mode
    layout = self.layout
        
    if manager.switch_object:
        col = layout.column()
        col.operator("ssm.switch_object", text="", icon="OBJECT_DATA")        
    if manager.switch_edit:
        col = layout.column()
        col.operator("ssm.switch_edit", text="", icon="EDITMODE_HLT")
        
    if manager.switch_pose:
        col = layout.column()
        col.operator("ssm.switch_pose", text="", icon="POSE_HLT")   
        
    if manager.switch_sculpt:
        col = layout.column()
        col.operator("ssm.switch_sculpt", text="", icon="SCULPTMODE_HLT")          
               

# Insert Keyfame for all Shape Keys
def draw_insert_kf_allsk(self, context):
    manager = context.scene.super_solid_mode
    if manager.all_skey:
        self.layout.operator("ssm.insert_keyf_allskey", text="Insert Keyframe for all")

# Video sequencer
def draw_video_sequencer(self, context):
    manager = context.scene.super_solid_mode
    layout = self.layout
    col = layout.column()
    col.label(text=' ')

    if manager.add_sound:
        col = layout.column()
        col.label(text=' ')
        col = layout.column()
        col.operator('sequencer.sound_strip_add', text='', icon='FILE_SOUND')

    if manager.add_movie:   
        col = layout.column()
        col.label(text=' ')
        col = layout.column()
        col.operator('sequencer.movie_strip_add', text='', icon='FILE_MOVIE')

    if manager.to_timeline_s:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_timeline_s', text='', icon='TIME')
        
    if manager.to_shader_editor_s:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_shader_editor_s', text='', icon="NODE_MATERIAL")
    
    if manager.to_dope_sheet_s:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_dope_sheet_s', text='', icon="ACTION")   
        
    if manager.to_graph_editor_s:
        col = layout.column()
        col.label(text=' ')     
        col = layout.column()
        col.operator('ssm.switch_to_graph_editor_s', text='', icon="GRAPH")   
      

# Undo and Redo
def draw_undo_redo(self, context):
    manager = context.scene.super_solid_mode
    if manager.undo_redo:
        self.layout.operator('ed.undo', text='', icon='LOOP_BACK')
        self.layout.operator('ed.redo', text='', icon='LOOP_FORWARDS')

# Deleting childless empties in a scene
def draw_delete_childless_empty_scene(self, context):
    self.layout.operator("ssm.delete_childless_emtpy_scene", text="", icon = "TRASH")

# Deleting childless empties in a collection
def draw_delete_childless_empty_collection(self, context):
    self.layout.operator("ssm.delete_childless_emtpy_collection", text="Delete Childless Empty")

# Deleting childless empties in object level
def draw_delete_childless_empty_object(self, context):
    self.layout.operator("ssm.delete_childless_emtpy_object", text="Delete Childless Empty")

# Automatic avtivation of Super Solid Mode
unique_name = str(uuid.uuid4())
addon_path = os.path.dirname(__file__)
text_path = os.path.join(addon_path, f"{unique_name}.log")
json_file = text_path = os.path.join(addon_path, f"{unique_name}.json")

@persistent
def auto_super_solid_mode(dummy):
    active_obj = bpy.context.active_object
    automode_activation_instances(json_file, addon_path, active_obj)

def sna_add_to_extremepbr_pt_mainpanel(self, context):
        if True:
            if bpy.context.scene.super_solid_mode.Extreme_pbr_patch:
                layout = self.layout
                layout.prop(context.scene.super_solid_mode, 'nodesetup', text="Node Setup", toggle=True, icon='TRIA_DOWN' if bpy.context.scene.super_solid_mode.nodesetup else 'TRIA_RIGHT')
                if  bpy.context.scene.super_solid_mode.nodesetup:
                    layout_box = layout.box()
                    layout_box.label(text='Convert Material to Nexus Node', icon_value=0)
                    row_0A5EE = layout_box.row(heading='Conveter', align=True)
                    row_0A5EE.alert = False
                    row_0A5EE.enabled = True
                    row_0A5EE.active = True
                    row_0A5EE.use_property_split = False
                    row_0A5EE.use_property_decorate = False
                    row_0A5EE.scale_x = 1.0
                    row_0A5EE.scale_y = 1.1
                    row_0A5EE.alignment = 'Expand'.upper()
                    row_0A5EE.operator_context = "INVOKE_DEFAULT" if True else "EXEC_DEFAULT"
                    op = row_0A5EE.operator('node.setup', text='Convert to Nexus Node', icon_value=127, emboss=True, depress=False)

from .ssm_operators import (
    SSM_OT_activate_diffuse_texture,
    SSM_OT_custom_normal,
    SSM_OT_forward_jump,
    SSM_OT_backward_jump,
    SSM_OT_delete_childless_emtpy_scene,
    SSM_OT_delete_childless_emtpy_collection,
    SSM_OT_delete_childless_emtpy_object,
    SSM_OT_insert_keyf_allskey,
    SSM_OT_switch_object,
    SSM_OT_switch_edit,
    SSM_OT_switch_pose,
    SSM_OT_switch_sculpt, 
    SSM_OT_switch_to_timeline_s,
    SSM_OT_switch_to_timeline_se,
    SSM_OT_switch_to_timeline_ds,     
    SSM_OT_switch_to_timeline_ge,    
    SSM_OT_switch_to_sequencer_t,
    SSM_OT_switch_to_sequencer_se,
    SSM_OT_switch_to_sequencer_ds,    
    SSM_OT_switch_to_sequencer_ge,
    SSM_OT_switch_to_shader_editor_t,
    SSM_OT_switch_to_shader_editor_s,
    SSM_OT_switch_to_shader_editor_ds,    
    SSM_OT_switch_to_shader_editor_ge,
    SSM_OT_switch_to_dope_sheet_t,
    SSM_OT_switch_to_dope_sheet_s,
    SSM_OT_switch_to_dope_sheet_se,
    SSM_OT_switch_to_dope_sheet_ge,    
    SSM_OT_switch_to_graph_editor_t,
    SSM_OT_switch_to_graph_editor_s,
    SSM_OT_switch_to_graph_editor_se,
    SSM_OT_switch_to_graph_editor_ds,    
    SSM_OT_frame_all,
    SSM_OT_jump_to_first,
    SSM_OT_jump_to_last
)

from .ssm_preferences import SSM_Preferences
from .ssm_panels import SSM_PT_normal_map_nodes
from .ssm_properties import SSM_Properties
from .ssm_patch_extreme_pbr import Nodesetup

classes = (
    SSM_OT_activate_diffuse_texture,
    SSM_Preferences,
    SSM_OT_custom_normal,
    SSM_PT_normal_map_nodes,
    SSM_Properties,
    SSM_OT_forward_jump,
    SSM_OT_backward_jump,
    SSM_OT_delete_childless_emtpy_scene,
    SSM_OT_delete_childless_emtpy_collection,
    SSM_OT_delete_childless_emtpy_object,
    SSM_OT_insert_keyf_allskey,
    SSM_OT_switch_object,
    SSM_OT_switch_edit,
    SSM_OT_switch_pose,
    SSM_OT_switch_sculpt,    
    SSM_OT_switch_to_timeline_s,
    SSM_OT_switch_to_timeline_se,
    SSM_OT_switch_to_timeline_ds,     
    SSM_OT_switch_to_timeline_ge,    
    SSM_OT_switch_to_sequencer_t,
    SSM_OT_switch_to_sequencer_se,
    SSM_OT_switch_to_sequencer_ds,    
    SSM_OT_switch_to_sequencer_ge,
    SSM_OT_switch_to_shader_editor_t,
    SSM_OT_switch_to_shader_editor_s,
    SSM_OT_switch_to_shader_editor_ds,    
    SSM_OT_switch_to_shader_editor_ge,
    SSM_OT_switch_to_dope_sheet_t,
    SSM_OT_switch_to_dope_sheet_s,
    SSM_OT_switch_to_dope_sheet_se,
    SSM_OT_switch_to_dope_sheet_ge,    
    SSM_OT_switch_to_graph_editor_t,
    SSM_OT_switch_to_graph_editor_s,
    SSM_OT_switch_to_graph_editor_se,
    SSM_OT_switch_to_graph_editor_ds,  
    SSM_OT_frame_all,
    SSM_OT_jump_to_first,
    SSM_OT_jump_to_last,
    Nodesetup
)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)
        
    bpy.types.TOPBAR_HT_upper_bar.draw_right = draw_activate_diffuse_texture
    bpy.types.TIME_MT_editor_menus.append(draw_ssm_frame_controls)
    bpy.types.VIEW3D_HT_header.append(draw_undo_redo)
    bpy.types.TOPBAR_HT_upper_bar.append(draw_topbar)
    bpy.types.OUTLINER_HT_header.append(draw_delete_childless_empty_scene)
    bpy.types.OUTLINER_MT_collection.append(draw_delete_childless_empty_collection)
    bpy.types.OUTLINER_MT_object.append(draw_delete_childless_empty_object)
    bpy.types.DATA_PT_shape_keys.append(draw_insert_kf_allsk)
    bpy.types.SEQUENCER_MT_editor_menus.append(draw_video_sequencer)
    bpy.types.NODE_MT_editor_menus.append(draw_shader_editor)
    bpy.types.GRAPH_MT_editor_menus.append(draw_graph_editor)
    bpy.types.DOPESHEET_MT_editor_menus.append(draw_dope_sheet)
    bpy.types.Scene.super_solid_mode = PointerProperty(type=SSM_Properties)
    bpy.app.handlers.depsgraph_update_post.append(auto_super_solid_mode)

    global _icons
    _icons = bpy.utils.previews.new()
    try:
        bpy.types.EXTREMEPBR_PT_MainPanel.append(sna_add_to_extremepbr_pt_mainpanel)
    except AttributeError:
        pass

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)

    bpy.types.TOPBAR_HT_upper_bar.draw_right = draw_activate_diffuse_texture.f
    bpy.types.TIME_MT_editor_menus.remove(draw_ssm_frame_controls)
    bpy.types.TOPBAR_HT_upper_bar.remove(draw_topbar)
    bpy.types.OUTLINER_HT_header.remove(draw_delete_childless_empty_scene)
    bpy.types.OUTLINER_MT_collection.remove(draw_delete_childless_empty_collection)
    bpy.types.OUTLINER_MT_object.remove(draw_delete_childless_empty_object)
    bpy.types.DATA_PT_shape_keys.remove(draw_insert_kf_allsk)
    bpy.types.SEQUENCER_MT_editor_menus.remove(draw_video_sequencer)
    bpy.types.NODE_MT_editor_menus.remove(draw_shader_editor)
    bpy.types.GRAPH_MT_editor_menus.remove(draw_graph_editor)
    bpy.types.DOPESHEET_MT_editor_menus.remove(draw_dope_sheet)
    del bpy.types.Scene.super_solid_mode

    try:
        bpy.app.handlers.depsgraph_update_post.remove(auto_super_solid_mode)
    except Exception as msg:
        print(f'unregister auto_super_solid_mode: {msg}')
        # pass
    
    global _icons
    bpy.utils.previews.remove(_icons)
    try:
       bpy.types.EXTREMEPBR_PT_MainPanel.remove(sna_add_to_extremepbr_pt_mainpanel)
    except AttributeError:
        pass
        

    


# if __name__ == "__main__":
#     register()