# -*- coding: utf-8 -*-
#
#   Copyright (C) 2019 Oslandia <infos@oslandia.com>
#
#   This file is a piece of free software; you can redistribute it and/or
#   modify it under the terms of the GNU Library General Public
#   License as published by the Free Software Foundation; either
#   version 2 of the License, or (at your option) any later version.
#
#   This library 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 library; if not, see <http://www.gnu.org/licenses/>.
#

from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QDialog, QVBoxLayout, QDialogButtonBox, QAbstractItemView
from qgis.PyQt.QtWidgets import (
    QListWidget,
    QListWidgetItem,
    QHBoxLayout,
    QLabel,
    QComboBox,
    QPushButton,
)
from PyQt5 import uic

from qgis.core import QgsProject, QgsFeatureRequest

from .qgeologis.data_interface import LayerData, FeatureData

import json
import os

from .qgeologis.units import AVAILABLE_UNITS


class DataStacker(QDialog):
    def __init__(self, viewer, features, plot_config, config, parent=None):
        """ DataSelector explore configuration to show log (to display or erase)

        """
        super().__init__(parent)

        uic.loadUi(os.path.join(os.path.dirname(__file__), "data_stacker.ui"), self)

        self.__viewer = viewer
        self.__features = features
        # config from selected item
        self.__data_type, self.__layer_config = plot_config
        self.__stacked = self.__layer_config["stacked"]
        self.__config = config

        self.__available = {}
        if "uom" in self.__layer_config:
            for k, v in AVAILABLE_UNITS.items():
                if self.__layer_config["uom"] in v:
                    self.__unit_type = k

            self.__available = self.__config.get_layer_config(self.__data_type, self.__unit_type)
            del self.__available[self.__layer_config["source"]]
        elif self.__layer_config["feature_filter_type"] == "unique_data_from_values":
            data_l = QgsProject.instance().mapLayers()[self.__layer_config["source"]]
            values = set()
            for feature in self.__features:
                feature_id = feature[self.__config["id_column"]]
                req = QgsFeatureRequest()
                req.setFilterExpression(
                    "{}={}".format(self.__layer_config["feature_ref_column"], feature_id)
                )
                values.update(
                    [
                        f[self.__layer_config["feature_filter_column"]]
                        for f in data_l.getFeatures(req)
                    ]
                )
            self.__available = {self.__layer_config["source"] + "#{}".format(v): v for v in values}

        self.__populate_lists()

        self._add_button.clicked.connect(self._add_stack)
        self._remove_button.clicked.connect(self._rm_stack)

    def __populate_lists(self):
        self._available_list.clear()
        self._stacked_list.clear()
        for k, v in self.__available.items():
            if k not in self.__stacked:
                item = QListWidgetItem(v)
                item.setData(Qt.UserRole, k)
                self._available_list.addItem(item)
            else:
                item = QListWidgetItem(v)
                item.setData(Qt.UserRole, k)
                self._stacked_list.addItem(item)

    def _add_stack(self):
        if len(self._available_list.selectedItems()) == 0:
            return

        for k, v in self.__available.items():
            if v == self._available_list.selectedItems()[0].text():
                self.__stacked[k] = v
        self.__populate_lists()

    def _rm_stack(self):
        if len(self._stacked_list.selectedItems()) == 0:
            return

        for k, v in self.__stacked.items():
            if v == self._stacked_list.selectedItems()[0].text():
                rm_k = k
        del self.__stacked[rm_k]
        self.__populate_lists()

    def stacked_items(self):
        return {
            self._stacked_list.item(i).data(Qt.UserRole): self._stacked_list.item(i).text()
            for i in range(0, self._stacked_list.count())
        }
