# -*- coding: utf-8 -*-
"""
S2_vn_rectangleDialog — draw rectangle on canvas search dialog.
"""

from __future__ import absolute_import

import os

from qgis.PyQt import uic
from qgis.PyQt.QtCore import QDate, pyqtSignal
from qgis.PyQt.QtWidgets import QDialog, QDialogButtonBox

from .ui.dialog_theme import apply_dialog_theme
from .ui.widgets import make_date_picker_only

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


class S2_vn_rectangleDialog(QDialog, FORM_CLASS):
    preview_requested = pyqtSignal()

    def __init__(self, iface, startX, startY, endX, endY, parent=None):
        super(S2_vn_rectangleDialog, self).__init__(parent)
        self.setupUi(self)
        apply_dialog_theme(self)

        self.iface = iface
        self.setCoordinates(startX, startY, endX, endY)

        self.time1.setDate(QDate.currentDate())
        self.time0.setDate(QDate.currentDate().addDays(-15))
        self.spin_cloud_threshold.setValue(20)

        make_date_picker_only(self.time0)
        make_date_picker_only(self.time1)
        self.btn_preview.clicked.connect(self.preview_requested.emit)

        self._ok_button = self.button_box.button(QDialogButtonBox.StandardButton.Ok)
        for line_edit in (self.wEdit, self.sEdit, self.eEdit, self.nEdit):
            line_edit.textChanged.connect(self._update_validation)
        self.time0.dateChanged.connect(self._update_validation)
        self.time1.dateChanged.connect(self._update_validation)
        for check_box in self._export_boxes():
            check_box.toggled.connect(self._update_filename_state)
        self._update_filename_state()
        self._update_validation()

    def cloud_threshold(self):
        return self.spin_cloud_threshold.value()

    def set_date_range(self, start_date, end_date):
        self.time0.setDate(start_date)
        self.time1.setDate(end_date)

    def bounding_box(self):
        """Return (west, south, east, north) as floats."""
        west, east = sorted((float(self.wEdit.text()), float(self.eEdit.text())))
        south, north = sorted((float(self.sEdit.text()), float(self.nEdit.text())))
        return west, south, east, north

    def _export_boxes(self):
        return (self.check, self.check_ndvi, self.check_nbr)

    def _update_filename_state(self):
        """The file name only matters once something is being exported."""
        exporting = any(box.isChecked() for box in self._export_boxes())
        self.label_filename.setEnabled(exporting)
        self.pre.setEnabled(exporting)

    def validation_message(self):
        """
        A problem worth spelling out, empty when there is none.

        The drawn rectangle already provides the area, so this dialog is ready
        to run as soon as it opens; only broken input is reported.
        """
        try:
            west, south, east, north = self.bounding_box()
        except ValueError:
            return u'Coordinates must be numbers / Tọa độ phải là số'
        if west == east or south == north:
            return u'The area has no width or height / ' \
                   u'Vùng chọn không có chiều rộng hoặc chiều cao'
        if self.time0.date() > self.time1.date():
            return u'The end date is before the start date / ' \
                   u'Ngày kết thúc trước ngày bắt đầu'
        return u''

    def _update_validation(self):
        message = self.validation_message()
        self.validationLabel.setText(message)
        self.validationLabel.setVisible(bool(message))
        ready = not message
        self._ok_button.setEnabled(ready)
        self.btn_preview.setEnabled(ready)

    def setCoordinates(self, startX, startY, endX, endY):
        if startX < endX:
            min_long = startX
            max_long = endX
        else:
            min_long = endX
            max_long = startX

        if startY < endY:
            min_lat = startY
            max_lat = endY
        else:
            min_lat = endY
            max_lat = startY

        self.wEdit.setText(str(min_long))
        self.sEdit.setText(str(min_lat))
        self.eEdit.setText(str(max_long))
        self.nEdit.setText(str(max_lat))
