
import ssl
from .blender_dialogue import openDialogue
import bpy
from urllib.request import urlopen
import base64
from pathlib import Path
import os
import urllib.request
import shutil

from .__meta__ import getName, getVersion
from .utils import getLatestVersion, openUrl, showMessage
from .utils_debug import debug_err, debug_log

didPerformUpdate = False
isUpdating = False

didShowUpdateButton = False
def checkIfUpdateIsAvailableAndShowDialogueWithButton(force=False):
    try:
        latestVersion = getLatestVersion()
        if latestVersion is None:
            return
        currentVersion = getVersion()
        if latestVersion != currentVersion:
            global didShowUpdateButton
            if didShowUpdateButton and not force:
                return
            didShowUpdateButton = True
            def draw(layout, context):
                layout.label(text="Click OK to update the 🌵 Needle Engine addon now")
                layout.label(text="Click Cancel or outside of the window to update later")
            openDialogue({
                "title": "🌵 Needle Blender Addon version is available",
                "draw": draw,
                # "accept": lambda self, context: openUrl("https://engine.needle.tools/downloads/blender/"),
                # "draw": self.drawDialogue,
                "accept": bpy.ops.needle.auto_update,
                # "cancel": None,
            })
    except Exception as e:
        debug_err("Failed to check if update is available and show dialogue with button", e)


def drawUpdateButton(layout, latestVersion:str, minimal=False, checkUpdateOnly=False):
    autoUpdateButtonLayout = layout.row(align=True)
    updateLabelText = "Automatic Update Addon to " + latestVersion
    if isUpdating:
        autoUpdateButtonLayout.enabled = False
        updateLabelText = "Updating..."
    elif didPerformUpdate:
        autoUpdateButtonLayout.enabled = False
        updateLabelText = "Restart Blender to complete update"
    if minimal == True:
        updateLabelText = ""
    if checkUpdateOnly and not didPerformUpdate:
        autoUpdateButtonLayout.operator("needle.check_for_update", text=updateLabelText, icon='LIGHT', depress=not isUpdating and not didPerformUpdate)
    else:
        autoUpdateButtonLayout.operator("needle.auto_update", text=updateLabelText, icon='LIGHT', depress=not isUpdating and not didPerformUpdate)

class Needle_OT_Check_For_Update(bpy.types.Operator):
    """Check for update"""
    bl_idname = "needle.check_for_update"
    bl_label = "Check for update"
    def execute(self, context):
        checkIfUpdateIsAvailableAndShowDialogueWithButton(force=True)
        return {'FINISHED'}

class Needle_OT_Auto_Update(bpy.types.Operator):
    """Download and install the latest version of Needle Engine"""
    bl_idname = "needle.auto_update"
    bl_label = "Update Needle Engine Addon"
    
    def execute(self, context):
        try:
            global isUpdating
            global didPerformUpdate

            if isUpdating:
                showMessage(["Already updating..."], "Addon Update", icon = 'INFO')
                return {'CANCELLED'}

            isUpdating = True
            if didPerformUpdate:
                showMessage(["Please restart Blender to complete update"], "Addon Update", icon = 'INFO')
                return {'FINISHED'}

            #Current ver URL
            current_ver_url = "https://engine.needle.tools/downloads/blender/download"
            current_ver_zip_name = "NeedleEngine_Blender.zip"
            addon_dir_name =  getName()
            import zipfile
    
            # Get the addons folder (alternative method)
            addons_path = Path(os.path.dirname(__file__)).parents[0]
            debug_log(f"Addons folder: {addons_path}")
            
            # Make our current directory the addons directory
            os.chdir(str(addons_path))
    
            # Download new SimbleBake_Current.zip to addons folder
            debug_log("Starting download from: " + current_ver_url)
            original_ssl_context = ssl._create_default_https_context
            try:
                ssl._create_default_https_context = ssl._create_unverified_context
                req = urllib.request.Request(current_ver_url, headers={'User-Agent': 'Needle Engine Blender Addon'})
                with urllib.request.urlopen(req) as response, open(current_ver_zip_name, 'wb') as out_file:
                    out_file.write(response.read())
                # urllib.request.urlretrieve(current_ver_url, current_ver_zip_name)
            finally:
                ssl._create_default_https_context = original_ssl_context
            debug_log("Download complete")
        
            #Delete current SimpleBake folder
            addon_dir = addons_path / addon_dir_name
            if addon_dir.exists():
                shutil.rmtree(str(addon_dir)) 
    
            # Unzip
            current_ver_zip = zipfile.ZipFile(current_ver_zip_name, "r")
            current_ver_zip.extractall()
            current_ver_zip.close()
        
            # Delete the downloaded zip
            downloaded_zip = addons_path / current_ver_zip_name
            downloaded_zip.unlink()
        
            # Report
            message_lines = ["Needle Engine Addon updated successfully", "Thank you for using Needle Engine", "Please restart Blender!"]
            showMessage(message_lines, "Needle Engine Addon Update complete", icon = 'INFO')
            didPerformUpdate = True

            # try:
            #     bpy.app.timers.register(lambda: openUrl("https://donate.needle.tools/"), first_interval=5)
            # except:
            #     pass
                        
            return {'FINISHED'}
        
        except Exception as e:
            debug_err("Failed to update addon", e)
            showMessage(["Failed to update addon:", "Please download the latest version manually by visiting", "https://engine.needle.tools/downloads/blender"], "Addon Update", icon = 'ERROR')
            return {'CANCELLED'}
        finally:
            isUpdating = False