from .operators_utils import openAddonPreferences
from .utils_license import hasLicense
from .utils_auth import getUserInformation
from .operators_web import buildDist, buildDistDelayed
from .settings_addon import getAddonPreferences
from .blender_windows import setStatus
from .utils_debug import debug_err, debug_log
import bpy
import os


from .external_process import getLogOutputToFileCommand

from .utils_web_project import getAssetsDirectory, getBuildDirectory, getTimeout
from .utils import getWebProjectPath, showMessage
from .utils_icons import getPreviewIcon



isDeploying = False

def getDeploymentName():
    name = os.path.basename(bpy.data.filepath)
    # if the blend file is not saved:
    if name == '':
        name = 'untitled'
    else:
        name = os.path.splitext(name)[0]
    return name
    

# class DeployToNeedlePanel(bpy.types.Panel):
#     bl_idname = "OBJECT_PT_NEEDLE_share"
#     bl_label = "Deploy To Needle Cloud"
#     bl_space_type = 'PROPERTIES'
#     bl_region_type = 'WINDOW'
#     bl_context = "scene"

#     def draw_header(self, context):
#         layout = self.layout
#         icon = getPreviewIcon("logo_small_bw")
#         layout.label(text="", icon_value=icon)
        
#     def draw(self, context):
#         drawDeployToSpacesUI(self, context)
#         pass

# def drawDeployToSpacesUI(self, context):
#     layout = self.layout
#     user = getUserInformation()
#     prefs = getAddonPreferences()
#     if not user or user.authenticated == False:
#         layout.operator("needle.open_preferences", text="Open Addon Preferences to Login", icon='PREFERENCES')
#         url = "https://cloud.needle.tools"
#         layout.operator("wm.url_open", text="Signup for Needle Cloud", icon="URL").url = url
#         return
    
#         # layout = layout.row(align=True)
#         # layout.enabled = False
#     global isDeploying
#     if isDeploying:
#         layout.enabled = False

#     prefs.drawTeamSelectionDropdown(prefs, layout, context)

#     # print deployment name

#     buttonText = "Upload to Needle Cloud"
#     deploymentButtons = layout.column(align=True)

#     if isDeploying:
#         buttonText = "Upload in progress..."
#     deployButtonLayout = deploymentButtons.row()
#     deployButtonLayout.scale_y = 2
#     deployButtonLayout.operator("needle.deploy_to_needle", text=buttonText, emboss=True, icon="EXPORT")
#     pass


def _needleSpacesDeploymentFinished():
    global isDeploying
    isDeploying = False
    # setStatus("Needle Cloud: Upload finished")
    # showMessage("Upload finished", "Needle Cloud")
    pass

class openNeedleShareUrlOp(bpy.types.Operator):
    bl_idname = 'needle.open_needle_share_url'
    bl_label = 'Open on Needle Cloud'
    bl_description = 'Opens the last deployed page'
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        if not context.scene.NEEDLE_deployment_needle_spaces.live_url:
            self.report({'ERROR'}, "No live URL available")
            return {'CANCELLED'}
        import webbrowser
        webbrowser.open(context.scene.NEEDLE_deployment_needle_spaces.live_url)
        pass

class deployToNeedleOp(bpy.types.Operator):
    bl_idname = 'needle.deploy_to_needle'
    bl_label = 'Deploy to Needle Cloud'
    bl_description = 'Deploy to Needle'
    bl_options = {'REGISTER', 'UNDO'}
    
    def execute(self, context):
        assets_dir = ''

        webProjectDir = getWebProjectPath()

        if webProjectDir:
            assets_dir = getAssetsDirectory(webProjectDir)
            if not assets_dir or not os.path.exists(assets_dir):
                self.report({'ERROR'}, "Could not find web directory: Please generate a web project first")
                return {'CANCELLED'}
        elif not webProjectDir:
            self.report({'ERROR'}, "Could not find web directory: Please generate a web project first")
            return {'CANCELLED'}
        
        user = getUserInformation()
        if not user or not user.authenticated:
            showMessage("Please login to your Needle Account", "Needle Cloud")
            bpy.app.timers.register(lambda: openAddonPreferences(context), first_interval=2, persistent=False)
            return {'CANCELLED'}
        
        # if not assets_dir or not os.path.exists(assets_dir):
        #     tempDir = bpy.app.tempdir
        #     temp_project_dir = tempDir + "/needle_share"
        #     assets_dir = temp_project_dir + "/assets"
        #     if not os.path.exists(assets_dir):
        #         os.makedirs(assets_dir)
        #     else:
        #         deleteDirectoryRecursive(assets_dir)
        #     debug_log("Exporting scene into temp directory:", assets_dir)
        #     exportScene(self, assets_dir, project_directory=temp_project_dir)
        
        global isDeploying
        if isDeploying:
            self.report({'ERROR'}, "Deployment is already in process")
            return {'CANCELLED'}
        try:
            isDeploying = True
            # showMessage("Preparing for launch!", "Needle Spaces")
            showMessage(["Uploading to Needle Cloud...", "The website will open when finished!", "Please check the terminal window for progress..."], "Needle Cloud")

            output_directory = getBuildDirectory(webProjectDir)
            preferences = getAddonPreferences()
            selected_team = preferences.selected_team

            if selected_team == None or len(selected_team) <= 0:
                self.report({'ERROR'}, "Please select a team in the addon preferences")
                isDeploying = False
                return {'CANCELLED'}
            
            # TODO: add project name selection, this currently just fails if the user has already one project deployed with a different name
            blend_file_name = getDeploymentName()

            projectNameParameter = "--name \"" + blend_file_name + "\""

            output_log_command = getLogOutputToFileCommand()
            cmd = f"echo Uploading to Needle Cloud: {blend_file_name} - Please wait... && npx --yes needle-cloud@version-1 deploy \"{output_directory}\" --org \"{selected_team}\" --open true {projectNameParameter} && echo \"\" && {getTimeout(60)}"
            # (No window opens? Please check 'Help/Needle/Open Current Log') &

            debug_log("Needle Cloud: Deploy command:\n", cmd)

            # run needle.build_dist operator
            # proc = buildDist(self, projectPath=webProjectDir, production=True, targetPlatform="web", postBuildCmd=cmd)
            buildDistDelayed(self, projectPath=webProjectDir, production=True, targetPlatform="web", postBuildCmd=cmd)
            bpy.app.timers.register(_needleSpacesDeploymentFinished, first_interval=10, persistent=True)

            # waitInterval = .3;
            # def waitForFinish():
            #     res = proc.poll()
            #     if res is not None:
            #         print("Finished: " + str(res))
            #         bpy.app.timers.unregister(waitForFinish)
            #         _needleSpacesDeploymentFinished()
            #         return None
            #     return waitInterval
            # bpy.app.timers.register(waitForFinish, first_interval=waitInterval, persistent=True)

            print("Deploying to Needle Cloud: \"" + output_directory + "\"")

            # if True:# context.scene.NEEDLE_deployment_needle_spaces.debug:
            #     cmd += " & " + getTimeout(100) 
            #     exec_command_standalone(cmd, cwd=output_directory)
                
            #     pass
            # else:
            #     exec_command(cmd, onMessage=_needleShareMessage, onClose=_needleSpacesDeploymentFinished)
        except Exception as e:
            self.report({'ERROR'}, "Error: " + str(e))
            isDeploying = False
            debug_err("Error deploying to needle", assets_dir, e)
            return {'CANCELLED'}
        return {'FINISHED'}


# def drawViewportMenuUI(self, context):
#     accessToken = _getAccessToken()
#     canShare = accessToken != None and len(accessToken) > 5
#     if canShare == False: return
#     layout = self.layout
#     layout.enabled = canShare
#     row = layout.row(align=True)
#     row.ui_units_x = 4.5
#     icon = getPreviewIcon("logo_small")
#     global isDeploying
#     if not isDeploying:
#         row.operator(deployToNeedleOp.bl_idname, text="Share", icon_value=icon)
#         open_url_op = row.row()
#         open_url_op.enabled = bpy.context.scene.NEEDLE_deployment_needle_spaces.live_url != None and len(bpy.context.scene.NEEDLE_deployment_needle_spaces.live_url) > 0
#         open_url_op.operator(openNeedleShareUrlOp.bl_idname, text="", icon="URL")
#     else:
#         row.enabled = False
#         row.operator(deployToNeedleOp.bl_idname, text="Uploading...", icon_value=icon)

# def register():
#     bpy.types.Scene.NEEDLE_deployment_needle_spaces = bpy.props.PointerProperty(type=NeedleShareProperties)

# def unregister():
#     try:
#         del bpy.types.Scene.NEEDLE_deployment_needle_spaces
#     except:
#         pass

