# Window.py -- Pamhyr
# Copyright (C) 2023-2026  INRAE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

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

import logging

from datetime import datetime
from tools import get_user_name

from Modules import Modules
from Model.Study import Study
from View.Tools.PamhyrWindow import PamhyrDialog

from PyQt5.QtCore import QCoreApplication

from PyQt5.QtGui import (
    QFont, QColor
)

from PyQt5.QtWidgets import (
    QRadioButton, QLabel, QDateTimeEdit,
    QTextEdit, QPlainTextEdit, QTextBrowser,
    QPushButton,
)

_translate = QCoreApplication.translate

logger = logging.getLogger()


class NewStudyWindow(PamhyrDialog):
    _pamhyr_ui = "NewStudy"
    _pamhyr_name = "Edit/New Study"

    def __init__(self, study=None, config=None, parent=None):
        if study is not None:
            name = (
                _translate("Study", "Edit study")
                + f" - {study.name}"
            )
        else:
            name = _translate("Study", "New study")

        super(NewStudyWindow, self).__init__(
            title=name,
            study=study,
            config=config,
            options=[],
            parent=parent
        )

        if self._study is not None:
            self.set_study_values()
        else:
            self.set_default_values()

        self.connection()

    def set_study_values(self):
        self.set_line_edit_text("lineEdit_name", self._study.name)
        self.set_plaintext_edit_text(
            "plainTextEdit_description", self._study.description
        )
        self.set_text_edit_text(
            "textBrowser_description", self._study.description
        )
        self.set_datetime_edit("dateTimeEdit_date", self._study.date)

        self.find(QLabel, "label_creation_date_data").setText(
            self._study.creation_date.isoformat(sep=" ")
        )
        self.find(QLabel, "label_last_modification_data").setText(
            self._study.last_save_date.isoformat(sep=" ")
        )

        if self._study.time_system == "date":
            self.set_radio_button("radioButton_date", True)
            self.find(QLabel, "label_date").setEnabled(True)
            self.find(QDateTimeEdit, "dateTimeEdit_date").setEnabled(True)

    def set_default_values(self):
        self.set_line_edit_text("lineEdit_name", "MyNewStudy")

        description = f"""# MyNewStudy

This is my new study description

---

## General information

...

## TODO

- [X] Network
- [ ] Geometry
- [ ] ...

## Change log

{datetime.now().strftime('%Y-%m-%d')}: Add a default bief

---

## Copyright

© {get_user_name()} - {datetime.now().year}

All right reserved.
"""

        self.set_plaintext_edit_text("plainTextEdit_description", description)
        self.set_text_edit_text("textBrowser_description", description)

    def connection(self):
        time = self.find(QRadioButton, "radioButton_time")
        date = self.find(QRadioButton, "radioButton_date")

        time.toggled.connect(self.set_time)
        date.toggled.connect(self.set_date)

        md_edit = self.find(QPlainTextEdit, "plainTextEdit_description")
        # md_preview = self.find(QTextBrowser, "textBrowser_description")
        md_edit.textChanged.connect(
            lambda: self.set_text_edit_text(
                "textBrowser_description",
                self.get_plaintext_edit_text(
                    "plainTextEdit_description"
                )
            )
        )

    def set_time(self):
        if self.get_radio_button("radioButton_time"):
            self.find(QLabel, "label_date").setEnabled(False)
            self.find(QDateTimeEdit, "dateTimeEdit_date").setEnabled(False)

    def set_date(self):
        if self.get_radio_button("radioButton_date"):
            self.find(QLabel, "label_date").setEnabled(True)
            self.find(QDateTimeEdit, "dateTimeEdit_date").setEnabled(True)

    def accept(self):
        name = self.get_line_edit_text("lineEdit_name")
        description = self.get_plaintext_edit_text("plainTextEdit_description")

        if self._study is None:
            study = Study.new(name, description)
            study.river.init_default()

            if self.get_radio_button("radioButton_date"):
                date = self.get_datetime_edit("dateTimeEdit_date")
                study.use_date(date)
            self.parent.set_model(study)
        else:
            self._study.name = name
            self._study.description = description
            if self.get_radio_button("radioButton_date"):
                date = self.get_datetime_edit("dateTimeEdit_date")
                self._study.use_date(date)
            else:
                self._study.use_time()

        self._propagate_update(key=Modules.STUDY)
        self.done(True)
