# -*- coding: utf-8 -*-
# ***************************************************************************
# *                                                                         *
# *   Copyright (c) 2017 - Amritpal Singh <amrit3701@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                                                                   *
# *                                                                         *
# ***************************************************************************

__title__ = "RebarCommands"
__author__ = "Amritpal Singh"
__url__ = "https://www.freecadweb.org"

import FreeCADGui, FreeCAD
from PySide import QtCore
from PySide.QtCore import QT_TRANSLATE_NOOP
from PVPlantResources import DirIcons as DirIcons
import os


class CommandPVPlantSite:
    "the PVPlant Site command definition"

    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "icon.svg")),
                'MenuText': QT_TRANSLATE_NOOP("Arch_Site", "Site"),
                'Accel': "S, I",
                'ToolTip': QT_TRANSLATE_NOOP("Arch_Site", "Creates a site object including selected objects.")}

    @staticmethod
    def IsActive():
        return ((not (FreeCAD.ActiveDocument is None)) and
                (FreeCAD.ActiveDocument.getObject("Site") is None))

    @staticmethod
    def Activated():
        import PVPlantSite
        PVPlantSite.makePVPlantSite()
        return


class CommandProjectSetup:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "flash.svg")),
                'Accel': "P, S",
                'MenuText': "Project Setup",
                'ToolTip': "Setup all the variable for this project"}

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

    @staticmethod
    def Activated():
        from Project import ProjectSetup
        taskd = ProjectSetup.ProjectSetupDialog()
        taskd.setParent(FreeCADGui.getMainWindow())
        taskd.setWindowFlags(QtCore.Qt.Window)
        taskd.show()


class CommandTerrain:
    "the PVPlant Terrain command definition"

    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "terrain.svg")),
                'MenuText': "Terrain",
                'Accel': "S, T",
                'ToolTip': "Creates a Terrain object from setup dialog."}

    @staticmethod
    def IsActive():
        return (not (FreeCAD.ActiveDocument is None) and
                not (FreeCAD.ActiveDocument.getObject("Site") is None) and
                (FreeCAD.ActiveDocument.getObject("Terrain") is None))

    @staticmethod
    def Activated():
        import PVPlantTerrain
        PVPlantTerrain.makeTerrain()
        # task = _TerrainTaskPanel()
        # FreeCADGui.Control.showDialog(task)
        return


class CommandCreateTerrainMesh:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "surface.svg")),
                'MenuText': QT_TRANSLATE_NOOP("PVPlant", "Create Surface"),
                'Accel': "C, S",
                'ToolTip': QT_TRANSLATE_NOOP("PVPlant", "Creates a surface form a cloud of points.")}

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

    @staticmethod
    def Activated():
        import PVPlantCreateTerrainMesh
        TaskPanel = PVPlantCreateTerrainMesh.TaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)


class CommandDivideArea:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "area.svg")),
                'Accel': "A, D",
                'MenuText': "Divide Area",
                'ToolTip': "Allowed Area"}

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

    @staticmethod
    def Activated():
        sel = FreeCADGui.Selection.getSelection()[0]


class CommandBoundary:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "area.svg")),
                'Accel': "A, B",
                'MenuText': "Area",
                'ToolTip': "Allowed Area"}

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

    @staticmethod
    def Activated():
        from Project.Area import PVPlantArea
        sel = FreeCADGui.Selection.getSelection()[0]
        obj = PVPlantArea.makeArea([ver.Point for ver in sel.Shape.Vertexes])
        # taskd = _PVPlantPlacementTaskPanel()
        # FreeCADGui.Control.showDialog(taskd)


class CommandFrameArea:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "FrameArea.svg")),
                'Accel': "A, F",
                'MenuText': "Frame Area",
                'ToolTip': "Frame Area"}

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

    @staticmethod
    def Activated():
        sel = FreeCADGui.Selection.getSelection()
        makeFramedArea(None, sel)


class CommandProhibitedArea:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "area_forbidden.svg")),
                'Accel': "A, F",
                'MenuText': "Prohibited Area",
                'ToolTip': "Prohibited Area"}

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

    @staticmethod
    def Activated():
        from Project.Area import PVPlantArea
        sel = FreeCADGui.Selection.getSelection()
        PVPlantArea.makeProhibitedArea(sel[0])


class CommandPVSubplant:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "subplant.svg")),
                'Accel': "A, P",
                'MenuText': "PV Subplant",
                'ToolTip': "PV Subplant"}

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

    @staticmethod
    def Activated():
        from Project.Area import PVPlantArea
        area = PVPlantArea.makePVSubplant()
        sel = FreeCADGui.Selection.getSelection()
        for obj in sel:
            if obj.Name[:7] == "Tracker":
                frame_list = area.Frames
                frame_list.append(obj)
                area.Frames = frame_list


class CommandOffsetArea:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "offset.svg")),
                'Accel': "A, O",
                'MenuText': "OffsetArea",
                'ToolTip': "OffsetArea"}

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

    @staticmethod
    def Activated():
        from Project.Area import PVPlantArea
        sel = FreeCADGui.Selection.getSelection()
        base = None
        if sel:
            base = sel[0]
        obj = PVPlantArea.makeOffsetArea(base)


class CommandSplitArea:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "split_area.svg")),
                'Accel': "A, S",
                'MenuText': "Split Area",
                'ToolTip': "Split Area"}

    @staticmethod
    def IsActive():
        return (not FreeCAD.ActiveDocument is None and
                not FreeCAD.ActiveDocument.findObjects(Name="ProhibitedArea") is None and
                not FreeCAD.ActiveDocument.findObjects(Name="OffsetArea") is None)

    @staticmethod
    def Activated():
        from Project.Area import PVPlantAreaUtils
        TaskPanel = PVPlantAreaUtils.splitAreaTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)
        return


class CommandJoinAreas:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "split_area.svg")),
                'Accel': "A, J",
                'MenuText': "Join Areas",
                'ToolTip': "Join Areas"}

    @staticmethod
    def IsActive():
        return (not FreeCAD.ActiveDocument is None and
                not FreeCAD.ActiveDocument.findObjects(Name="ProhibitedArea") is None and
                not FreeCAD.ActiveDocument.findObjects(Name="OffsetArea") is None)

    @staticmethod
    def Activated():
        from Project.Area import PVPlantAreaUtils
        TaskPanel = PVPlantAreaUtils.splitAreaTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)
        return


class CommandContours:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "TerrainContours.svg")),
                'Accel': "T, C",
                'MenuText': 'Curvas de nivel',
                'ToolTip': 'Curvas de nivel'
                }

    @staticmethod
    def IsActive():
        # return not FreeCAD.ActiveDocument is None
        if FreeCAD.ActiveDocument is None:
            return False
        return True
        if FreeCADGui.Selection.getSelection() is not None:
            selection = FreeCADGui.Selection.getSelection()[-1]
            if selection.TypeId == 'Mesh::Feature':
                return True
        return False

    @staticmethod
    def Activated():
        import PVPlantTerrainAnalisys
        TaskPanel = PVPlantTerrainAnalisys.ContourTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)


class CommandSlopeAnalisys:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "TerrainSlope.svg")),
                'Accel': "T, S",
                'MenuText': 'Analisis de Pendiente',
                'ToolTip': 'Analisis de Pendiente'
                }

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

    @staticmethod
    def Activated():
        import PVPlantTerrainAnalisys
        TaskPanel = PVPlantTerrainAnalisys.SlopeTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)


class CommandHeightAnalisys:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "TerrainHeight.svg")),
                'Accel': "T, H",
                'MenuText': 'Analisis de Altura',
                'ToolTip': 'Analisis de Altura'
                }

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

    @staticmethod
    def Activated():
        import PVPlantTerrainAnalisys
        TaskPanel = PVPlantTerrainAnalisys.HeightTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)


class CommandOrientationAnalisys:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "TerrainOrientation.svg")),
                'Accel': "T, H",
                'MenuText': 'Analisis de Orientación',
                'ToolTip': 'Analisis de Orientación'}

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

    @staticmethod
    def Activated():
        import PVPlantTerrainAnalisys
        TaskPanel = PVPlantTerrainAnalisys.OrientationTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)


class CommandTrench:  # V1:
    """Gui command for the Line tool."""

    @staticmethod
    def GetResources():
        """Set icon, menu and tooltip."""
        return {'Pixmap': str(os.path.join(DirIcons, "trench.svg")),
                'MenuText': "Trench",
                'Accel': "C, T",
                'ToolTip': "Creates a Trench object from setup dialog."}

    @staticmethod
    def IsActive():
        active = not (FreeCAD.ActiveDocument is None)
        terrain = not (FreeCAD.ActiveDocument.getObject("Terrain") is None)
        active = active and terrain
        if terrain:
            active = active and not (FreeCAD.ActiveDocument.getObject("Terrain").Mesh is None)
        return active

    @staticmethod
    def Activated():
        """Execute when the command is called."""
        from Civil import PVPlantTrench
        sel = FreeCADGui.Selection.getSelection()
        done = False

        if len(sel) > 0:
            import Draft
            for obj in sel:
                if Draft.getType(obj) == "Wire":
                    FreeCAD.ActiveDocument.openTransaction("Create Trench")
                    PVPlantTrench.makeTrench(obj)
                    FreeCAD.ActiveDocument.commitTransaction()
                    FreeCAD.ActiveDocument.recompute()
                    done = True
                    break

        if not done:
            taskd = PVPlantTrench.TrenchTaskPanel()
            if taskd:
                FreeCADGui.Control.showDialog(taskd)
            else:
                print(" No ha sido posible crear el formulario")


class CommandSemiAutomaticTrench:  # V1:
    """Gui command for the Line tool."""

    @staticmethod
    def GetResources():
        """Set icon, menu and tooltip."""
        return {'Pixmap': str(os.path.join(DirIcons, "trench.svg")),
                'MenuText': "Semi-Automatic Trench Generator",
                'Accel': "T, S",
                'ToolTip': "Creates a Trench object from setup dialog."}

    @staticmethod
    def IsActive():
        active = not (FreeCAD.ActiveDocument is None)
        terrain = not (FreeCAD.ActiveDocument.getObject("Terrain") is None)
        active = active and terrain
        if terrain:
            active = active and not (FreeCAD.ActiveDocument.getObject("Terrain").Mesh is None)
        return active

    @staticmethod
    def Activated():
        """Execute when the command is called."""
        from Civil import PVPlantTrench
        semi = PVPlantTrench.semiAutomaticTrench()


class CommandCalculateEarthworks:
    @staticmethod
    def GetResources():
        return {'Pixmap': str(os.path.join(DirIcons, "pico.svg")),
                'Accel': "C, E",
                'MenuText': QT_TRANSLATE_NOOP("Placement", "Movimiento de tierras"),
                'ToolTip': QT_TRANSLATE_NOOP("Placement", "Calcular el movimiento de tierras")}

    @staticmethod
    def IsActive():
        active = not (FreeCAD.ActiveDocument is None)
        if not (FreeCAD.ActiveDocument.getObject("Terrain") is None):
            active = active and not (FreeCAD.ActiveDocument.getObject("Terrain").Mesh is None)
        return active

    @staticmethod
    def Activated():
        import PVPlantEarthWorks
        TaskPanel = PVPlantEarthWorks.EarthWorksTaskPanel()
        FreeCADGui.Control.showDialog(TaskPanel)


class CommandManhole:
    "the PVPlant Manhole command definition"

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

    @staticmethod
    def IsActive():
        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

    @staticmethod
    def Activated():
        import PVPlantManhole
        task_panel = PVPlantManhole._ManholeTaskPanel()
        FreeCADGui.Control.showDialog(task_panel)
        return


if FreeCAD.GuiUp:
    FreeCADGui.addCommand('PVPlantSite', CommandPVPlantSite())
    import PVPlantGeoreferencing

    FreeCADGui.addCommand('PVPlantGeoreferencing', PVPlantGeoreferencing.CommandPVPlantGeoreferencing())
    FreeCADGui.addCommand('ProjectSetup', CommandProjectSetup())
    FreeCADGui.addCommand('Terrain', CommandTerrain())
    FreeCADGui.addCommand('PVPlantCreateTerrainMesh', CommandCreateTerrainMesh())


    class CommandAreaGroup:
        @staticmethod
        def GetCommands():
            return tuple([  # 'Area',
                'FrameArea',
                'ForbiddenArea',
                'PVSubplant',
                'OffsetArea'
            ])

        @staticmethod
        def GetResources():
            return {'MenuText': 'Areas',
                    'ToolTip': 'Areas'
                    }

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


    # FreeCADGui.addCommand('Area', CommandBoundary())
    FreeCADGui.addCommand('FrameArea', CommandFrameArea())
    FreeCADGui.addCommand('ForbiddenArea', CommandProhibitedArea())
    FreeCADGui.addCommand('PVSubplant', CommandPVSubplant())
    FreeCADGui.addCommand('OffsetArea', CommandOffsetArea())
    FreeCADGui.addCommand('PVPlantAreas', CommandAreaGroup())

    FreeCADGui.addCommand('SplitArea', CommandSplitArea())
    FreeCADGui.addCommand('JoinAreas', CommandJoinAreas())


    class CommandTerrainAnalisysGroup:
        @staticmethod
        def GetCommands():
            return tuple(['Contours',
                          'HeightAnalisys',
                          'SlopeAnalisys',
                          'OrientationAnalisys'
                          ])

        @staticmethod
        def GetResources():
            return {'MenuText': QT_TRANSLATE_NOOP("", 'Terrain Analisys'),
                    'ToolTip': QT_TRANSLATE_NOOP("", 'Terrain Analisys')
                    }

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


    FreeCADGui.addCommand('Contours', CommandContours())
    FreeCADGui.addCommand('SlopeAnalisys', CommandSlopeAnalisys())
    FreeCADGui.addCommand('HeightAnalisys', CommandHeightAnalisys())
    FreeCADGui.addCommand('OrientationAnalisys', CommandOrientationAnalisys())
    FreeCADGui.addCommand('TerrainAnalisys', CommandTerrainAnalisysGroup())


    class CommandTrenchGroup:
        @staticmethod
        def GetCommands():
            return tuple(['PVPlantTrench',
                          'PVPlantSemiAutomaticTrench',
                          ])

        @staticmethod
        def GetResources():
            return {'MenuText': 'Rack Types',
                    'ToolTip': 'Rack Types'
                    }

        @staticmethod
        def IsActive():
            active = not (FreeCAD.ActiveDocument is None)
            terrain = not (FreeCAD.ActiveDocument.getObject("Terrain") is None)
            active = active and terrain
            if terrain:
                active = active and not (FreeCAD.ActiveDocument.getObject("Terrain").Mesh is None)
            return active


    FreeCADGui.addCommand('PVPlantTrench', CommandTrench())
    FreeCADGui.addCommand('PVPlantSemiAutomaticTrench', CommandSemiAutomaticTrench())
    FreeCADGui.addCommand('Trenches', CommandTrenchGroup())
    FreeCADGui.addCommand('PVPlantEarthworks', CommandCalculateEarthworks())

    FreeCADGui.addCommand('PVPlantManhole', CommandManhole())

    import PVPlantPlacement
    FreeCADGui.addCommand('PVPlantPlacement', PVPlantPlacement.CommandPVPlantPlacement())
    FreeCADGui.addCommand('PVPlantAdjustToTerrain', PVPlantPlacement.CommandAdjustToTerrain())
    FreeCADGui.addCommand('PVPlantConvertTo', PVPlantPlacement.CommandConvert())

    import hydro.hydrological as hydro
    FreeCADGui.addCommand('HydrologicalAnalysis', hydro.CommandHydrologicalAnalysis())

    import Vegetation.PVPlantTreeGenerator as TreeGenerator
    FreeCADGui.addCommand('PVPlantTree', TreeGenerator.CommandTree())

    import Project.GenerateExternalDocument as GED
    FreeCADGui.addCommand('newExternalDocument', GED.CommandGenerateExternalDocument())

    from Mechanical.Frame import PVPlantFrame
    class CommandRackGroup:

        def GetCommands(self):
            return tuple(['PVPlantFixedRack',
                          'PVPlantTrackerSetup',
                          'PVPlantTracker'
                          ])

        def GetResources(self):
            return {'MenuText': QT_TRANSLATE_NOOP("", 'Rack Types'),
                    'ToolTip': QT_TRANSLATE_NOOP("", 'Rack Types')
                    }

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

    FreeCADGui.addCommand('PVPlantFixedRack', PVPlantFrame.CommandFixedRack())
    FreeCADGui.addCommand('PVPlantTrackerSetup', PVPlantFrame.CommandTrackerSetup())
    FreeCADGui.addCommand('PVPlantTracker', PVPlantFrame.CommandTracker())
    FreeCADGui.addCommand('RackType', CommandRackGroup())

from Civil.Fence import PVPlantFence
FreeCADGui.addCommand('PVPlantFenceGroup', PVPlantFence.CommandFenceGroup())

import docgenerator
FreeCADGui.addCommand('GenerateDocuments', docgenerator.generateDocuments())

projectlist = [  # "Reload",
    "PVPlantSite",
    "ProjectSetup",
    "PVPlantGeoreferencing",
    "Separator",
    # "ImportGrid",
    "Terrain",
    "TerrainAnalisys",
    "PVPlantCreateTerrainMesh",
    "Separator",
    # "PointsGroup",
    "PVPlantAreas",
    "SplitArea",
    "Separator",
    "Trenches",
    "PVPlantEarthworks",
    # "PVPlantPad",
    # "PVPlantRoad",
    "PVPlantManhole",
    # "PVPlantFoundation"
    # "GraphTerrainProfile",
    # "Trace",
    "Separator",
    'HydrologicalAnalysis',
    'newExternalDocument',
]

pv_mechanical = [
    "RackType",
    "PVPlantPlacement",
    "PVPlantAdjustToTerrain",
    "PVPlantConvertTo",
]

objectlist = ['PVPlantTree',
              'PVPlantFenceGroup',
              'GenerateDocuments',
              ]