import os
import FreeCADGui as Gui
import FreeCAD as App
from PySide.QtCore import QT_TRANSLATE_NOOP
import shutil
ICONPATH = os.path.join(os.path.dirname(__file__), "resources")
zone = "StabilityZone"
import requests
import importOBJ


class AddStabilityZone:
    def __init__(self):
        pass

    def GetResources(self):
        return {'Pixmap': os.path.join(ICONPATH, "stability_zone.svg"),
                'Accel': "Ctrl+A",
                'MenuText': QT_TRANSLATE_NOOP("My_Command", "My Command"),
                'ToolTip': QT_TRANSLATE_NOOP("My_Command", "Runs my command in the active document")}

    def Activated(self):
        App.ActiveDocument.addObject("Part::Box", "Box")
        App.ActiveDocument.ActiveObject.Label = zone
        selected_object = App.ActiveDocument.getObjectsByLabel(zone)[0]
        selected_object.ViewObject.Transparency = 50
        selected_object.ViewObject.ShapeColor = (0.15, 0.80, 0.50)
        pass

    def IsActive(self):
        return True


class SyncServer:
   
    httpURL = None
    def __init__(self, httpURL):
        self.httpURL = httpURL
 

    def GetResources(self):
        return {'Pixmap': os.path.join(ICONPATH, "server_sync.svg"),
                'Accel': "Ctrl+A",
                'MenuText': QT_TRANSLATE_NOOP("My_Command", "My Command"),
                'ToolTip': QT_TRANSLATE_NOOP("My_Command", "Runs my command in the active document")}

    def Activated(self):
        StabilityZone = App.ActiveDocument.getObjectsByLabel(zone)
        dir_path = os.path.dirname(os.path.realpath(__file__))
        dir_out = dir_path + '/out/'
        if not os.path.exists(dir_out):
            os.makedirs(dir_out)
        importOBJ.export(StabilityZone, u"" + dir_out + 'StabilityZone.obj')
        shutil.make_archive(dir_out + '/' + 'geometry', 'zip',)
        zipArch = dir_out +  'geometry.zip'
        requests.post(url=self.httpURL,  files={'zip': open(zipArch, "rb")})
        shutil.rmtree(dir_out)
        pass

    def IsActive(self):
        return True


class StabilityWorkbench(Gui.Workbench):

    MenuText = "stability workbench"
    ToolTip = "a simple template workbench"
    Icon = os.path.join(ICONPATH, "template_resource.svg")
    toolbox = ['AddStabilityZone', 'SyncServer']
    httpURL = None
    def __init__(self,httpURL):
        self.httpURL = httpURL
 

    def GetClassName(self):
        return "Gui::PythonWorkbench"

    def Initialize(self):
        Gui.addCommand('AddStabilityZone', AddStabilityZone())
        Gui.addCommand('SyncServer', SyncServer(
            self.httpURL))
        self.appendToolbar("Tools", self.toolbox)
        self.appendMenu("Tools", self.toolbox)

    def Activated(self):
        pass

    def Deactivated(self):
        pass
