# -*- coding: utf-8 -*-

__author__ = '(C) 2023 by Gerald Kogler'
__date__ = '1/10/2023'
__copyright__ = 'Copyright 2023, 300.000 Km/s'
__license__ = 'GPLv3 license'

import os
import glob
import shutil
import pathlib

from qgis.PyQt import uic
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt import QtWidgets
from qgis.PyQt.QtWidgets import QLineEdit, QVBoxLayout, QCheckBox, QPushButton, QDialogButtonBox

from qgis.gui import QgsFileWidget
from qgis.core import QgsApplication, QgsProject, Qgis

from .utils import Utils

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'qwv_dialog2_base.ui'))


class QWVDialog2(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, iface, parent=None):
        """Constructor."""
        super(QWVDialog2, self).__init__(parent)
        # Set up the user interface from Designer through FORM_CLASS.
        # After self.setupUi() you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect

        self.iface = iface
        self.setupUi(self)

        # add buttons
        self.runBtn = QPushButton(Utils.getIcon("system-run"), Utils.tr("Run"))
        self.button_box.addButton(self.runBtn, QDialogButtonBox.ApplyRole)

        self.saveBtn = QPushButton(Utils.getIcon("document-save"), Utils.tr("Save Settings"))
        self.button_box.addButton(self.saveBtn, QDialogButtonBox.ActionRole)

        self.closeBtn = QPushButton(Utils.getIcon("window-close"), Utils.tr("Close"))
        self.button_box.addButton(self.closeBtn, QDialogButtonBox.ActionRole)

        self.helpBtn = QPushButton(Utils.getIcon("help"), Utils.tr("Help"))
        self.button_box.addButton(self.helpBtn, QDialogButtonBox.HelpRole)

        self.dialog2_mapsets_list = []
        self.dialog2_folder.fileChanged.connect(self.loadMapsets)

        # load default output folder
        if self.dialog2_output.filePath() == "":
            self.dialog2_output.setFilePath(QgsProject.instance().readPath("./"))

        # prepare Logos table
        self.addRowLogo()
        self.dialog2_addlogo.clicked.connect(self.addRowLogo)
        self.dialog2_removelogo.clicked.connect(self.removeRowLogo)

        # prepare Attachment table
        self.addRowAttachment()
        self.dialog2_addfile.clicked.connect(self.addRowAttachment)
        self.dialog2_removefile.clicked.connect(self.removeRowAttachment)


    def addRowLogo(self, file=None, name=None, url=None):
        """Add row to logos table."""

        index = self.dialog2_logos.rowCount()
        self.dialog2_logos.insertRow(index)

        dialog2_logos_file = QgsFileWidget()
        if file:
            dialog2_logos_file.setFilePath(file)
        self.dialog2_logos.setCellWidget(index, 0, dialog2_logos_file)

        dialog2_logos_name = QLineEdit()
        if name:
            dialog2_logos_name.setText(name)
        self.dialog2_logos.setCellWidget(index, 1, dialog2_logos_name)

        dialog2_logos_url = QLineEdit()
        if url:
            dialog2_logos_url.setText(url)
        self.dialog2_logos.setCellWidget(index, 2, dialog2_logos_url)


    def removeRowLogo(self):
        """Remove row from logos table."""

        selectedRows = self.dialog2_logos.selectionModel().selectedRows()

        if len(selectedRows) > 0:
            self.dialog2_logos.removeRow(selectedRows[0].row())


    def addRowAttachment(self, file=None, name=None):
        """Add row to attachment table."""

        index = self.dialog2_attachments.rowCount()
        self.dialog2_attachments.insertRow(index)

        dialog2_attachments_file = QgsFileWidget()
        if file:
            dialog2_attachments_file.setFilePath(file)
        self.dialog2_attachments.setCellWidget(index, 0, dialog2_attachments_file)

        dialog2_attachments_name = QLineEdit()
        if name:
            dialog2_attachments_name.setText(name)
        self.dialog2_attachments.setCellWidget(index, 1, dialog2_attachments_name)


    def removeRowAttachment(self):
        """Remove row from attachment table."""

        selectedRows = self.dialog2_attachments.selectionModel().selectedRows()

        if len(selectedRows) > 0:
            self.dialog2_attachments.removeRow(selectedRows[0].row())


    def loadMapsets(self):
        """Show all mapsets in list."""

        # print("loadMapsets", self.dialog2_folder.filePath())

        self.mapset_layout = self.dialog2_mapsets.layout()

        if self.mapset_layout == None:
            # insert new layout
            self.mapset_layout = QVBoxLayout()
            self.dialog2_mapsets.setLayout(self.mapset_layout)

        # remove all widgets
        self.dialog2_mapsets_list = []
        for widget in self.dialog2_mapsets.findChildren(QCheckBox):
            self.mapset_layout.removeWidget(widget)

        # Get all files ending with .json:
        filesCheck = []
        for root, dirs, files in os.walk(self.dialog2_folder.filePath()):
            for file in files:
                if file.endswith(".json"):
                    filesCheck.append(os.path.join(root, file))

        # order files and add checkboxes
        for file in sorted(filesCheck):
            checkbox = QCheckBox(file)
            self.dialog2_mapsets_list.append(checkbox)
            self.mapset_layout.insertWidget(len(self.dialog2_mapsets_list)-1, checkbox)


    def setupResources(self):
        """Copy viewer and tileserver into project folder and put mbtiles, conf.json and logo and attachment files into place."""

        # copy tileserver and viewer
        settingsPath = QgsApplication.qgisSettingsDirPath()
        resourcePath = os.path.join(os.path.dirname(__file__), 'resources/viewer')
        outputPath = self.dialog2_output.filePath()
        viewerFolder = 'viewer_' + Utils.toAsciiAlnum(self.dialog2_title.text())
        viewerPath = os.path.join(outputPath, viewerFolder)
        dataPath = os.path.join(viewerPath, 'data')

        shutil.copytree(resourcePath, viewerPath, dirs_exist_ok=True)

        # move conf.json
        exportPath = self.dialog2_folder.filePath()
        shutil.move(os.path.join(exportPath, 'conf.json'), os.path.join(dataPath, 'conf.json'))

        # copy all mbtiles
        tilePath = os.path.join(dataPath, 'tileserver')

        for mapsetCheckbox in self.dialog2_mapsets_list:
            if mapsetCheckbox.isChecked():
                mapsetFile = mapsetCheckbox.text()
                mapsetFile = mapsetFile.replace('.json', '')
                filestartMbtiles = os.path.basename(mapsetFile)

                # copy all mbtiles files from dataPath to viewer/data/tileserver
                mapsetPath = self.dialog2_folder.filePath()
                for root, dirs, files in os.walk(mapsetPath):
                    for file in files:
                        if viewerPath not in os.path.join(root, file) and file.startswith(filestartMbtiles) and file.endswith(".mbtiles"):
                            fileMbtiles = os.path.join(root, file)
                            shutil.copy2(fileMbtiles, tilePath)

                # copy mapset attachment files from export/data to viewer/data
                mapsetAttachPath = os.path.join(os.path.dirname(mapsetFile), 'data')
                shutil.copytree(mapsetAttachPath, dataPath, dirs_exist_ok=True)

        # make folders logos and attachments
        logosPath = os.path.join(dataPath, 'logos')
        attachmentsPath = os.path.join(dataPath, 'attachments')
        if not os.path.exists(logosPath):
            os.makedirs(logosPath)
        if not os.path.exists(attachmentsPath):
            os.makedirs(attachmentsPath)

        # copy logo files to viewer/data
        for i in range(self.dialog2_logos.rowCount()):
            file = self.dialog2_logos.cellWidget(i, 0).filePath()
            if os.path.exists(file):
                shutil.copy2(file, logosPath)

        # copy attachment files to viewer/data
        for i in range(self.dialog2_attachments.rowCount()):
            file = self.dialog2_attachments.cellWidget(i, 0).filePath()
            if os.path.exists(file):
                shutil.copy2(file, attachmentsPath)


    def isMapsetChecked(self):
        """At least one mapsets_list element is checked."""

        for mapsetCheckbox in self.dialog2_mapsets_list:
            if mapsetCheckbox.isChecked():
                return True

        return False