# /**********************************************************************
# *                                                                     *
# * 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

if FreeCAD.GuiUp:
    import FreeCADGui, os
    from PySide import QtCore
    from PySide.QtCore import QT_TRANSLATE_NOOP
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 PVPlantResources


def makeCable(name="Cable"):
    obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name)
    obj.Label = name
    Cable(obj)
    ViewProviderCable(obj.ViewObject)
    return obj


class Cable(ArchComponent.Component):
    "A Cable Obcject - Class"

    def __init__(self, obj):
        ArchComponent.Component.__init__(self, obj)
        self.setProperties(obj)

    def setProperties(self, obj):
        pl = obj.PropertiesList

        # General:
        if not ("Manufacturer" in pl):
            obj.addProperty("App::PropertyString",
                            "Manufacturer",
                            "General",
                            "Connection")

        if not ("Factory" in pl):
            obj.addProperty("App::PropertyString",
                            "Factory",
                            "General",
                            "Connection ")

        if not ("DesignStandard" in pl):
            obj.addProperty("App::PropertyString",
                            "DesignStandard",
                            "General",
                            "Connection ")

        if not ("CableDesignation" in pl):
            obj.addProperty("App::PropertyString",
                            "CableDesignation",
                            "General",
                            "Connection ").CableDesignation="RH5Z1-OL"

        if not ("MaximumVoltage" in pl):
            obj.addProperty("App::PropertyElectricPotential",
                            "MaximumVoltage",
                            "General",
                            "Connection ").MaximumVoltage="30kV"

        if not ("MaxTemperatureForContinuousOperation" in pl):
            obj.addProperty("App::PropertyInteger",
                            "MaxTemperatureForContinuousOperation",
                            "General",
                            "Connection ").MaxTemperatureForContinuousOperation=95

        if not ("MaxTemperatureDuringEmergencyConditions" in pl):
            obj.addProperty("App::PropertyInteger",
                            "MaxTemperatureDuringEmergencyConditions",
                            "General",
                            "Connection ").MaxTemperatureDuringEmergencyConditions=105

        if not ("MaxTemperatureDuringShortCircuit" in pl):
            obj.addProperty("App::PropertyInteger",
                            "MaxTemperatureDuringShortCircuit",
                            "General",
                            "Connection ").MaxTemperatureDuringShortCircuit=250


        # Conductor:
        if not ("Material" in pl):
            obj.addProperty("App::PropertyEnumeration",
                            "Material",
                            "Conductor",
                            "Connection ").Material=["Copper", "Aluminium"]

        if not ("Standard" in pl):
            obj.addProperty("App::PropertyString",
                            "Standard",
                            "Conductor",
                            "Connection ").Standard = "IEC 60228"

        if not ("CrossSection" in pl):
            obj.addProperty("App::PropertyArea",
                            "CrossSection",
                            "Conductor",
                            "Connection ").CrossSection = 95

        if not ("MaximumConductorDiameter" in pl):
            obj.addProperty("App::PropertyLength",
                            "MaximumConductorDiameter",
                            "Conductor",
                            "Connection ")

        if not ("MinimumConductorDiameter" in pl):
            obj.addProperty("App::PropertyLength",
                            "MinimumConductorDiameter",
                            "Conductor",
                            "Connection ")

        if not ("MaximumResistance" in pl):
            obj.addProperty("App::PropertyInteger",
                            "MaximumResistance",
                            "Conductor",
                            "Connection ")

        # Insulation:
        if not ("InsulationMaterial" in pl):
            obj.addProperty("App::PropertyEnumeration",
                            "InsulationMaterial",
                            "Insulation",
                            "Connection ").InsulationMaterial=["HEPR", "XLPE"]

        if not ("InsulationStandard" in pl):
            obj.addProperty("App::PropertyString",
                            "InsulationStandard",
                            "Insulation",
                            "Connection ").InsulationStandard = "IEC 60502-2"

        if not ("InsulationNominalThickness" in pl):
            obj.addProperty("App::PropertyLength",
                            "InsulationNominalThickness",
                            "Insulation",
                            "Sección").InsulationNominalThickness = 7.25

        if not ("InsulationMinimumThickness" in pl):
            obj.addProperty("App::PropertyLength",
                            "InsulationMinimumThickness",
                            "Insulation",
                            "Sección").InsulationMinimumThickness = 6.43

        if not ("InsulationResistance" in pl):
            obj.addProperty("App::PropertyInteger",
                            "InsulationResistance",
                            "Insulation",
                            "Sección").InsulationResistance = 3670000

        # Outer semi-conductive layer:
        if not ("OuterMaterial" in pl):
            obj.addProperty("App::PropertyString",
                            "OuterMaterial",
                            "OuterLayer",
                            "Connection ").OuterMaterial = "Semicon. compound"

        if not ("OuterNominalThickness" in pl):
            obj.addProperty("App::PropertyLength",
                            "OuterNominalThickness",
                            "OuterLayer",
                            "Sección").OuterNominalThickness = 0.5

        if not ("OuterMinimumThickness" in pl):
            obj.addProperty("App::PropertyLength",
                            "OuterMinimumThickness",
                            "OuterLayer",
                            "Sección").OuterMinimumThickness = 0.5

        # algo
        if not ("ExternalDiameter" in pl):
            obj.addProperty("App::PropertyDistance",
                            "ExternalDiameter",
                            "Cable",
                            QT_TRANSLATE_NOOP("App::Property", "Diameter")).ExternalDiameter = 6.6

        if not ("Section" in pl):
            obj.addProperty("App::PropertyArea",
                            "Section",
                            "Cable",
                            QT_TRANSLATE_NOOP("App::Property", "Sección"))

        if not ("Core" in pl):
            obj.addProperty("App::PropertyEnumeration",
                            "Core",
                            "Cable",
                            "Core").Core = ["1", "2", "3", ]

        if not ("RadiusOfCurvature" in pl):
            obj.addProperty("App::PropertyDistance",
                            "RadiusOfCurvature",
                            "Cable",
                            QT_TRANSLATE_NOOP("App::Property", "Diameter")).RadiusOfCurvature = 100

        self.Type = "Cable"

        obj.Proxy = self
        obj.IfcType = "Cable Segment"
        obj.setEditorMode("IfcType", 1)

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

        ArchComponent.Component.onDocumentRestored(self, obj)
        self.setProperties(obj)
        obj.Proxy = self

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

    def getPoint(self, val):
        if val.Proxy.Type == 'String':
            return val.StringPoles[0]
        elif val.Proxy.Type == 'StringBox':
            input = val.Shape.SubShapes[2].SubShapes[0]
            return input.CenterOfMass
        else:
            return val.Placement.Base

    def execute(self, obj):
        ''' No hacer nada. Es un componente sin shape'''


class ViewProviderCable(ArchComponent.ViewProviderComponent):   #hace falta??
    def __init__(self, vobj):
        ArchComponent.ViewProviderComponent.__init__(self, vobj)

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


class CommandCable:
    def GetResources(self):
        return {'Pixmap': str(os.path.join(PVPlantResources.DirIcons, "cable.svg")),
                'Accel': "E, C",
                'MenuText': QT_TRANSLATE_NOOP("Placement", "Cable"),
                'ToolTip': QT_TRANSLATE_NOOP("Placement", "Calcular el BOQ de la")}

    def Activated(self):
        makeCable()
        FreeCAD.ActiveDocument.recompute()

    def IsActive(self):
        if FreeCAD.ActiveDocument:
            return True
        else:
            return False


if FreeCAD.GuiUp:
    FreeCADGui.addCommand('PVPlantCable', CommandCable())
