# coding=UTF-8

import os

from PyQt5.QtWidgets import QDialog
from PyQt5 import uic
from PyQt5.Qt import QDoubleValidator, QIntValidator, QLocale

from qgis.core import QgsProject, QgsMapLayer
from .qgeologis.units import AVAILABLE_UNITS, unitConversionFactor

DEFAULT_PLOT_SIZE = 150


class EditPlot(QDialog):
    def __init__(self, item, legend, uom, displayed_uom=None, parent=None):
        super(EditPlot, self).__init__(parent)

        uic.loadUi(os.path.join(os.path.dirname(__file__), "edit_plot.ui"), self)
        self.setWindowTitle(legend.title())

        if uom == "unused":
            self._unit_cb.setEnabled(False)
            self._min_value.setEnabled(False)
            self._max_value.setEnabled(False)
            self.log_scale_chk.setEnabled(False)
            self._uncertainty_cb.setEnabled(False)
            self.label.setEnabled(False)
            self.label_2.setEnabled(False)
            self.label_3.setEnabled(False)
            self.label_6.setEnabled(False)
        else:
            if uom == "Categorical":
                # Unit change not set for categorical data
                self._unit_cb.setEnabled(False)
                self._factor = 1.0
            else:
                self._uom = uom
                self._factor = None
                for k, v in AVAILABLE_UNITS.items():
                    if uom in v:
                        self._unit_cb.addItems(v)
                        self._unit_cb.setCurrentText(displayed_uom)
                if uom != displayed_uom:
                    self._factor = unitConversionFactor(self._uom, displayed_uom)
                else:
                    self._factor = 1.0
                self._unit_cb.currentIndexChanged.connect(self.__apply_factor)

                validator = QDoubleValidator()
                validator.setLocale(QLocale("C"))
                self._min_value.setValidator(validator)
                self._max_value.setValidator(validator)

                self.log_scale_chk.setChecked(True if item.scale_type() == "log" else False)
                self._min_value.setText(str((item.data_window().y()) * self._factor))
                self._max_value.setText(
                    str((item.data_window().height() + item.data_window().y()) * self._factor)
                )

                self._uncertainty_cb.addItems(item.layer().fields().names())
                if item.uncertainty_column() is not None:
                    self._uncertainty_cb.setCurrentText(item.uncertainty_column())

        validator = QIntValidator()
        validator.setLocale(QLocale("C"))
        self._plot_size.setValidator(validator)
        self._plot_size.setText(str(int(item.height() if legend.is_vertical() else item.width())))

    def __apply_factor(self):
        min_val = float(self._min_value.text()) * 1 / self._factor
        max_val = float(self._max_value.text()) * 1 / self._factor
        self._factor = unitConversionFactor(self._uom, self._unit_cb.currentText())
        self._min_value.setText(str(min_val * self._factor))
        self._max_value.setText(str(max_val * self._factor))

    def plot_config(self):
        return (
            self.log_scale_chk.isChecked(),
            self._unit_cb.currentText() if self._unit_cb.isEnabled() else None,
            float(self._min_value.text()) * 1 / self._factor
            if self._min_value.text() != ""
            else None,
            float(self._max_value.text()) * 1 / self._factor
            if self._max_value.text() != ""
            else None,
            self._uncertainty_cb.currentText()
            if self._uncertainty_cb.currentText() != "None"
            else None,
            int(self._plot_size.text() if self._plot_size.text() != "" else DEFAULT_PLOT_SIZE),
        )
