# /**********************************************************************
# *                                                                     *
# * Copyright (c) 2021 Javier Braña <javier.branagutierrez@gmail.com>  *
# *                                                                     *
# * This program is free software; you can redistribute it and/or modify*
# * it under the terms of the GNU Lesser General Public License (LGPL)  *
# * as published by the Free Software Foundation; either version 2 of   *
# * the License, or (at your option) any later version.                 *
# * for detail see the LICENCE text file.                               *
# *                                                                     *
# * This program is distributed in the hope that it will be useful,     *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of      *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the       *
# * GNU Library General Public License for more details.                *
# *                                                                     *
# * You should have received a copy of the GNU Library General Public   *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307*
# * USA                                                                 *
# *                                                                     *
# ***********************************************************************

import ArchComponent
import FreeCAD
import Part

if FreeCAD.GuiUp:
    import FreeCADGui
    from PySide import QtCore
    import draftguitools.gui_trackers as DraftTrackers
else:
    # \cond
    def translate(ctxt, txt):
        return txt
    def QT_TRANSLATE_NOOP(ctxt, txt):
        return txt
    # \endcond

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

import os
import PVPlantResources
from PVPlantResources import DirIcons as DirIcons


def makeModule(name="Module"):
    obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name)
    obj.Label = name
    Module(obj)
    ViewProviderModule(obj.ViewObject)
    FreeCAD.ActiveDocument.recompute()
    return obj


class Module(ArchComponent.Component):
    "A Manhole Obcject"

    def __init__(self, obj):
        # Definición de Variables:
        ArchComponent.Component.__init__(self, obj)
        self.setProperties(obj)

    def setProperties(self, obj):
        pl = obj.PropertiesList
        # Base de datos: -----------------------------------------------------------------------------------------------
        if not ("Manufacturer" in pl):
            obj.addProperty("App::PropertyStringList",
                            "Manufacturer",
                            "Module",
                            "The manufacturer of this object"
                            )

        if not ("Model" in pl):
            obj.addProperty("App::PropertyStringList",
                            "Model",
                            "Module",
                            "The model of this object"
                            )

        # Dimensions: --------------------------------------------------------------------------------------------------
        if not ("Height" in pl):
            obj.addProperty("App::PropertyLength",
                            "Height",
                            "Manhole",
                            "The height of this object"
                            ).Height = 2804

        if not ("Width" in pl):
            obj.addProperty("App::PropertyLength",
                            "Width",
                            "Manhole",
                            "The width of this object"
                            ).Width = 1303

        if not ("Thickness" in pl):
            obj.addProperty("App::PropertyLength",
                            "Thickness",
                            "Manhole",
                            "The height of this object"
                            ).Thickness = 35

        # Electrical: --------------------------------------------------------------------------------------------------
        if not ("Power" in pl):
            obj.addProperty("App::PropertyPower",
                            "Power",
                            "Outputs",
                            "The height of this object"
                            ).Power = 650

        if not ("Umpp" in pl):
            obj.addProperty("App::PropertyElectricCurrent",
                            "Umpp",
                            "Outputs",
                            "The height of this object"
                            ).Umpp = 650

        if not ("Impp" in pl):
            obj.addProperty("App::PropertyElectricCurrent",
                            "Impp",
                            "Outputs",
                            "The height of this object"
                            ).Impp = 650

        if not ("Uoc" in pl):
            obj.addProperty("App::PropertyElectricCurrent",
                            "Uoc",
                            "Outputs",
                            "The height of this object"
                            ).Uoc = 650

        if not ("Isc" in pl):
            obj.addProperty("App::PropertyElectricCurrent",
                            "Isc",
                            "Outputs",
                            "The height of this object"
                            ).Isc = 650

        if not ("Isc" in pl):
            obj.addProperty("App::PropertyElectricCurrent",
                            "Impp",
                            "Outputs",
                            "The height of this object"
                            ).Impp = 650

        self.Type = "Module"
        obj.Proxy = self

    def onDocumentRestored(self, obj):
        """Method run when the document is restored.
        Re-adds the Arch component, and Arch wall properties."""
        ArchComponent.Component.onDocumentRestored(self, obj)
        self.setProperties(obj)

    def onChanged(self, obj, prop):
        '''Do something when a property has changed'''

    def execute(self, obj):
        box = Part.makeBox(obj.Width, obj.Height, obj.Thickness)
        box.translate(FreeCAD.Vector(-obj.Width, -obj.Height, 0) / 2)
        obj.Shape = box


class ViewProviderModule(ArchComponent.ViewProviderComponent):
    "A View Provider for the Module object"

    def __init__(self, vobj):
        ArchComponent.ViewProviderComponent.__init__(self, vobj)

    def getIcon(self):
        return str(os.path.join(DirIcons, "manhole.svg"))

    def setEdit(self, vobj, mode):
        """Method called when the document requests the object to enter edit mode.

        Edit mode is entered when a user double clicks on an object in the tree
        view, or when they use the menu option [Edit -> Toggle Edit Mode].

        Just display the standard Arch component task panel.

        Parameters
        ----------
        mode: int or str
            The edit mode the document has requested. Set to 0 when requested via
            a double click or [Edit -> Toggle Edit Mode].

        Returns
        -------
        bool
            If edit mode was entered.
        """

        if (mode == 0) and hasattr(self, "Object"):
            taskd = _ManholeTaskPanel(self.Object)
            taskd.obj = self.Object
            # taskd.update()
            FreeCADGui.Control.showDialog(taskd)
            return True

        return False


class ManholeTaskPanel:
    def __init__(self, obj=None):
        self.new = False
        if obj is None:
            self.new = True
            obj = makeManhole()

        self.obj = obj

        self.form = FreeCADGui.PySideUic.loadUi(PVPlantResources.__dir__ + "/PVPlantManhole.ui")

        self.node = None
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.tracker = DraftTrackers.ghostTracker(obj)
        self.tracker.on()
        self.call = self.view.addEventCallback("SoEvent", self.action)

    def action(self, arg):
        """Handle the 3D scene events.

        This is installed as an EventCallback in the Inventor view.

        Parameters
        ----------
        arg: dict
            Dictionary with strings that indicates the type of event received
            from the 3D view.
        """

        if arg["Type"] == "SoKeyboardEvent" and arg["Key"] == "ESCAPE":
            self.finish()

        elif arg["Type"] == "SoLocation2Event":
            point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg)
            if info:
                self.tracker.move(FreeCAD.Vector(info["x"], info["y"], info["z"]))
            else:
                self.tracker.move(point)

        elif (arg["Type"] == "SoMouseButtonEvent" and
              arg["State"] == "DOWN" and
              arg["Button"] == "BUTTON1"):

            point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg)
            if info:
                self.obj.Placement.Base = FreeCAD.Vector(info["x"], info["y"], info["z"])
            else:
                self.obj.Placement.Base = point
            self.finish()

    def finish(self):
        self.accept()

    def accept(self):
        self.closeForm()
        return True

    def reject(self):
        if self.new:
            FreeCAD.ActiveDocument.removeObject(self.obj.Name)
        self.closeForm()
        return True

    def closeForm(self):
        self.tracker.finalize()
        FreeCADGui.Control.closeDialog()
        self.view.removeEventCallback("SoEvent", self.call)


'''class _CommandManhole:
    "the Arch Building command definition"

    def GetResources(self):
        return {'Pixmap': str(os.path.join(DirIcons, "manhole.svg")),
                'MenuText': "Manhole",
                'Accel': "C, M",
                'ToolTip': "Creates a Manhole object from setup dialog."}

    def IsActive(self):
        return not FreeCAD.ActiveDocument is None

        if FreeCAD.ActiveDocument is not None:
            if FreeCADGui.Selection.getCompleteSelection():
                for ob in FreeCAD.ActiveDocument.Objects:
                    if ob.Name[:4] == "Site":
                        return True

    def Activated(self):
        TaskPanel = _ManholeTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)
        return


if FreeCAD.GuiUp:
    FreeCADGui.addCommand('PVPlantManhole', _CommandManhole())'''

