from .utils_license import hasLicense
from .blender_export import BuildContext, exportScene
import bpy
from .utils_system_requirements import getMaxSupportedNodeVersion, hasSupportedNodeVersionInstalled
from .utils_web_project import getOpenUrlCommand, getTimeout, openInBrowser, runBuild
from .external_process import exec_command_standalone
from .utils_icons import getPreviewIcon
from .utils import getChangeDirectoryCommand, getWebProjectPath

class DeployToGlitchPanel(bpy.types.Panel):
    bl_idname = "OBJECT_PT_NEEDLE_deploy_glitch"
    bl_label = "Needle Deploy To Glitch"
    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)
        glitch_idon = getPreviewIcon("glitch")
        layout.label(text="", icon_value=glitch_idon)

    def draw(self, context):
        _hasCommercialLicense = hasLicense()
        hasProjectName = context.scene.NEEDLE_deployment_glitch_project_name != ""
        hasProjectKey = context.scene.NEEDLE_deployment_glitch_project_key != ""
        
        
        if(_hasCommercialLicense == False):
            layout = self.layout
            row = layout.row(align=True)
            row.enabled = False
            layout.label(text="Deployment to Glitch requires a Needle license", icon="ERROR")
            # button to open pricing
            row = layout.row(align=True)
            row.enabled = True
            row.operator("needle.open_url", text="Open licensing options", icon="URL").url = "https://needle.tools/pricing"
            return

        if hasSupportedNodeVersionInstalled() == False:
            layout = self.layout
            layout.enabled = False
            layout.label(text="Deployment to Glitch requires a supported Nodejs version. Please install Node " + getMaxSupportedNodeVersion(), icon="ERROR")
            return
        
        path =  getWebProjectPath()
        if path == None:
            self.layout.enabled = False

        layout = self.layout
        el = layout.column(align=True)

        el.prop(context.scene, "NEEDLE_deployment_glitch_project_name", text="Project Name")
        if not hasProjectName:
            el.label(text="Please paste your project URL", icon="ERROR")
        else:
            row = el.row(align=True)
            row.prop(context.scene, "NEEDLE_deployment_glitch_project_key", text="Key")
            editOp = row.operator("needle.open_url", text="", icon="COPYDOWN")
            editOp.url = "https://glitch.com/edit/#!/" + context.scene.NEEDLE_deployment_glitch_project_name + "?path=.env%3A1%3A0"
            if  not hasProjectKey:
                el.label(text="Please enter the deployment key from the .env file on glitch", icon="ERROR")

        el.separator()

        row = el.row(align=True)
        if hasProjectName:
            editOp = row.operator("needle.open_url", text="Edit on Glitch", icon="URL")
            editOp.url = "https://glitch.com/edit/#!/" + context.scene.NEEDLE_deployment_glitch_project_name
            viewOp = row.operator("needle.open_url", text="View Live", icon="URL")
            viewOp.url = "https://" + context.scene.NEEDLE_deployment_glitch_project_name + ".glitch.me"
        else:
            row.operator("needle.remix_glitch", text="Create a new project on Glitch", icon="URL")

        el.separator()
        buttons = el.row(align=True)
        buttons.enabled = hasProjectName and hasProjectKey
        buttons.operator("needle.deploy_to_glitch", text="Deploy to Glitch", emboss=True, icon="EXPORT")
        

    
class deployToGlitchOp(bpy.types.Operator):
    bl_idname = 'needle.deploy_to_glitch'
    bl_label = 'Deploy To Glitch'
    bl_options = {"REGISTER"}
    bl_description = "Deploy the current project to Glitch.com"

    production = bpy.props.BoolProperty(name="Production", default=True)

    def execute(self, context):

        project = getWebProjectPath()
        if project is None:
            return {"FINISHED"}

        # export
        ctx = BuildContext()
        ctx.targetPlatform = "glitch"
        exportScene(self, context=ctx, building_dist=True)

        toolpath = project + "/node_modules/@needle-tools/helper"
        script_name = "workflow:deploy-to-glitch"
        glitch_url = context.scene.NEEDLE_deployment_glitch_project_name
        glitch_key = context.scene.NEEDLE_deployment_glitch_project_key

        cmd = getTimeout(2) + " && " + getChangeDirectoryCommand(toolpath) +  " && "
        cmd += "npm run " + script_name + " -- --directory \"" + project + "\""
        cmd += " --glitch \"" + glitch_url + "\""
        cmd += " --key \"" + glitch_key + "\""

        glitchUrl = "https://" + glitch_url + ".glitch.me"
        cmd += " && " + getTimeout(2) + " && " + getOpenUrlCommand(glitchUrl)
        cmd += " && echo \"Deployment finished. Opening Glitch project in browser on " + glitchUrl + "\""
        cmd += " & " + getTimeout(2)
        # cmd += " && timeout 5"
        runBuild(project, self.production, cmd)
        return {"FINISHED"} 

    
class remixGlitch(bpy.types.Operator):
    bl_idname = 'needle.remix_glitch'
    bl_label = 'Deploy To Glitch'
    bl_options = {"REGISTER"}
    bl_description = "Create a new project on Glitch.com"

    def execute(self, context):
        name = "needle-tiny-starter"
        url = "https://glitch.com/edit/#!/remix/" + name
        # open in browser
        openInBrowser(url)
        return {"FINISHED"} 


def onGlitchProjectNameChanged(self, context):
    # parse project name from url
    url = context.scene.NEEDLE_deployment_glitch_project_name
    if url == "":
        return
    if "edit/#!" in url:
        url = url.split("edit/#!")[1]
    if "?" in url:
        url = url.split("?")[0]
    if url.startswith("https://"):
        url = url[8:]
    url = url.replace("glitch.me", "")
    while url.startswith("/"):
        url = url[1:]
    while url.endswith("/") or url.endswith("#") or url.endswith("."):
        url = url[:-1]
    if url != context.scene.NEEDLE_deployment_glitch_project_name:
        context.scene.NEEDLE_deployment_glitch_project_name = url
    




def register():
    bpy.types.Scene.NEEDLE_deployment_glitch_project_name = bpy.props.StringProperty(name="Glitch Project Name", update=onGlitchProjectNameChanged)
    bpy.types.Scene.NEEDLE_deployment_glitch_project_key = bpy.props.StringProperty(name="Glitch Project Key", subtype="PASSWORD")

def unregister():
    try:
        del bpy.types.Scene.NEEDLE_deployment_glitch_project_name
        del bpy.types.Scene.NEEDLE_deployment_glitch_project_key
    except:
        pass

