# /**********************************************************************
# *                                                                     *
# * 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
import Draft
import os
import platform
import subprocess
import openpyxl
from openpyxl.styles import Alignment, Border, Side, Font

from PVPlantPlacement import getCols

if FreeCAD.GuiUp:
    from DraftTools import translate
    from PySide.QtCore import QT_TRANSLATE_NOOP

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

def open_file(path):
    """Open a file or directory using the default system handler"""
    if platform.system() == "Windows":
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])


from PVPlantPlacement import getCols

def generateLayout(numcells = 3, gapc = 3):
    # TODO: hacerlo por zonas

    objects = []
    for obj in FreeCAD.ActiveDocument.Objects:
        if not hasattr(obj, "Proxy"):
            continue
        '''if issubclass(obj.Proxy.__class__, PVPlantRack.Frame):
            objects.append(obj)'''
        if obj.Name.startswith("Tracker") and not obj.Name.startswith("TrackerSetup"):
            objects.append(obj)

    if len(objects) == 0:
        FreeCAD.Console.PrintError("No hay trackes" + "\n")
        return False

    columns = getCols(objects.copy())

    MaxY = max(objects, key=lambda obj: obj.Placement.Base.y).Placement.Base.y
    long_max = max(objects, key=lambda obj: obj.Setup.Length.Value).Setup.Length.Value
    num_pole_max = max(objects, key=lambda obj: obj.Setup.NumberPole.Value).Setup.NumberPole.Value
    num_module_max = max(objects, key=lambda obj: obj.Setup.ModuleColumns.Value).Setup.ModuleColumns.Value
    # TODO: calcular la serparación entre trackers.
    gapy = 500

    import openpyxl
    path = os.path.dirname(FreeCAD.ActiveDocument.FileName)
    filename = os.path.join(path, "layout.xlsx")
    mywb = openpyxl.Workbook()

    # 1. Hincas
    sheet = mywb.active
    sheet.title = 'Poles'
    m = -(numcells * num_pole_max + gapc) / (long_max + gapy)
    line = lambda x: int(m * (x - MaxY))
    drawLayout(sheet, columns, line, 0)

    # 2. Paneles
    sheet = mywb.create_sheet("Modules")
    m = -(numcells * num_module_max + gapc) / (long_max + gapy)
    line = lambda x: int(m * (x - MaxY) + 1)
    #drawLayout(sheet, columns, line, 1)

    mywb.save(filename)
    print("Se ha generado el lyout en excel satisfactoriamente en: ")
    print(filename)
    os.startfile(path)

    #from os import startfile
    #startfile("archivo.txt")

    return True

def drawLayout(sheet, cols, line, cnt = 0, numcell = 3, gap = 3):
    from openpyxl.styles import Alignment, Border, Side, PatternFill, GradientFill, Font
    thin = Side(border_style="thin", color="000000")

    for i, col in enumerate(cols):
        colnum = i * 3 + 1
        for g, group in enumerate(col):
            rownum = int(line(group[0].Placement.Base.y)) + 1
            if rownum < 1:
                continue
            for frame in group:
                num = int(frame.Setup.NumberPole.Value if cnt == 0 else frame.Setup.ModuleColumns.Value)
                sheet.merge_cells(start_row=rownum, start_column=colnum,
                                  end_row=rownum, end_column=colnum + 1)
                titlecell = sheet.cell(row=rownum, column=colnum)
                titlecell.value = frame.Label
                titlecell.border = Border(top=thin, left=thin, right=thin, bottom=thin)
                titlecell.font = Font(b=True, color="FF0000")
                titlecell.alignment = Alignment(horizontal="center", vertical="center")
                rownum += 1
                for ind in range(num):
                    sheet.merge_cells(start_row=rownum, start_column=colnum,
                                      end_row=rownum + numcell - 1, end_column=colnum)
                    polecell = sheet.cell(row=rownum, column=colnum)
                    polecell.value = ind + 1
                    polecell.alignment = Alignment(horizontal="center", vertical="center")

                    sheet.merge_cells(start_row=rownum, start_column=colnum + 1,
                                      end_row=rownum + numcell - 1, end_column=colnum + 1)
                    polecell = sheet.cell(row=rownum, column=colnum + 1)
                    polecell.value = "Celda-" + str(ind + 1)
                    polecell.value = frame.Label
                    polecell.border = Border(top=thin, left=thin, right=thin, bottom=thin)
                    polecell.font = Font(b=True, color="FF0000")
                    polecell.alignment = Alignment(horizontal="center", vertical="center")

                    rownum += numcell
                rownum += 1

