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

if FreeCAD.GuiUp:
    import FreeCADGui
    import os
else:
    # \cond
    def translate(ctxt, txt):
        return txt


    def QT_TRANSLATE_NOOP(ctxt, txt):
        return txt
    # \endcond

__title__ = "PVPlant Area Utils"
__author__ = "Javier Braña"
__url__ = "http://www.sogos-solar.com"

import PVPlantResources


def splitArea(area, tool):
    if (not area) or (not tool):
        return None

    import Part, TechDraw
    import BOPTools.SplitAPI as splitter
    tool = tool.Shape
    if tool.BoundBox.ZMax != tool.BoundBox.ZMin:
        tool = TechDraw.projectEx(tool, FreeCAD.Vector(0, 0, 1))[0]
    tool = tool.extrude(FreeCAD.Vector(0, 0, 1000))
    tool.Placement.Base.z -= 500

    shape = area.Shape
    if shape.BoundBox.ZMax != shape.BoundBox.ZMin:
        shape = TechDraw.projectEx(shape, FreeCAD.Vector(0, 0, 1))[0]
    face = Part.Face(Part.Wire(shape.Edges))

    return splitter.slice(face, [tool, ], "Split")


class splitAreaTaskPanel:
    def __init__(self):
        self.area = None
        self.tool = None

        self.form = FreeCADGui.PySideUic.loadUi(os.path.join(PVPlantResources.__dir__, "Project", "Area", "PVPlantSplitArea.ui"))
        self.form.buttonAreaSel.clicked.connect(self.addArea)
        self.form.buttonToolSel.clicked.connect(self.addTool)

        #self.view = FreeCADGui.ActiveDocument.ActiveView
        #self.call = self.view.addEventCallback("SoEvent", self.action)

    def addArea(self):
        self.area = FreeCADGui.Selection.getSelection()[0]
        self.form.lineArea.setText(self.area.Name)

    def addTool(self):
        self.tool = FreeCADGui.Selection.getSelection()[0]
        self.form.lineTool.setText(self.tool.Name)

    def accept(self):
        import Part
        self.closeForm()
        results = splitArea(self.area, self.tool)
        if isinstance(results, Part.Compound):
            for face in results.Faces:
                Part.show(face.Wire, self.area.Label + "-split")
        elif isinstance(results, list):
            for face in results:
                Part.show(face.Wire, self.area.Label + "-split")
        else:
            Part.show(results)


        if self.form.checkBoxDeleteTool.isChecked():
            FreeCAD.ActiveDocument.removeObject(self.tool.Name)
        if self.form.checkBoxDeleteArea.isChecked():
            FreeCAD.ActiveDocument.removeObject(self.area.Name)
        return True

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

    def closeForm(self):
        print(" .. Closing .. ")
        #self.view.removeEventCallback("SoEvent", self.call)
        FreeCADGui.Control.closeDialog()

def joinAreas(areas):
    if len(areas) == 0:
        return None

    import TechDraw
    shapes = []
    for area in areas:
        shape = area.Shape
        if shape.BoundBox.ZMax != shape.BoundBox.ZMin:
            shape = TechDraw.projectEx(shape, FreeCAD.Vector(0, 0, 1))[0]
        shapes.append(shape)
    shape = shapes.pop()
    shape.fuse(shapes)
    return shape

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

    def IsActive(self):
        return (not FreeCAD.ActiveDocument is None and
                not FreeCAD.ActiveDocument.findObjects(Name="ProhibitedArea") is None and
                not FreeCAD.ActiveDocument.findObjects(Name="OffsetArea") is None)
    def Activated(self):
        self.TaskPanel = splitAreaTaskPanel()
        FreeCADGui.Control.showDialog(self.TaskPanel)
        return

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

    def IsActive(self):
        return (not FreeCAD.ActiveDocument is None and
                not FreeCAD.ActiveDocument.findObjects(Name="ProhibitedArea") is None and
                not FreeCAD.ActiveDocument.findObjects(Name="OffsetArea") is None)
    def Activated(self):
        self.TaskPanel = splitAreaTaskPanel()
        FreeCADGui.Control.showDialog(self.TaskPanel)
        return

if FreeCAD.GuiUp:
    FreeCADGui.addCommand('SplitArea', CommandSplitArea())
    FreeCADGui.addCommand('JoinAreas', CommandJoinAreas())'''


