# PamhyrWidget.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, timedelta

from PyQt5.QtCore import (
    QModelIndex, QRect, QTime, QDateTime,
)

from PyQt5.QtWidgets import (
    QSpinBox, QTimeEdit, QDateTimeEdit, QItemDelegate,
)

from View.Tools.ASubWindow import AWidget

logger = logging.getLogger()


class PamhyrWidget(AWidget):
    _pamhyr_ui = None
    _pamhyr_name = "PamhyrWidget"

    def __init__(self, parent=None):
        super(PamhyrWidget, self).__init__(
            ui=self._pamhyr_ui,
            parent=parent
        )


class PamhyrExtendedTimeEdit(AWidget):
    def __init__(self, parent=None):
        super(PamhyrExtendedTimeEdit, self).__init__(
            ui="extendedTimeEdit",
            parent=parent
        )
        self.parent = parent

        self.spinBox_days = self.find(QSpinBox, "spinBox_days")
        self.timeEdit = self.find(QTimeEdit, "timeEdit")

    def set_time(self, time):
        days = 0
        stime = time

        # if ',' in time, time format is 'DD days, HH:MM:SS',
        # otherelse is 'HH:MM:SS'
        if "," in time:
            s = time.strip().split(" ")
            days = int(s[0])
            stime = s[-1]

        qtime = QTime.fromString(
            stime,
            "h:mm:ss"
        )
        self.spinBox_days.setValue(days)
        self.timeEdit.setTime(qtime)

    def get_time(self):
        days = self.spinBox_days.value()
        time = self.timeEdit.time().toPyTime()
        secs = (
            (time.hour * 3600) +
            (time.minute * 60) +
            time.second
        )

        return timedelta(days=days, seconds=secs)


class PamhyrExtendedDateTimeEdit(AWidget):
    def __init__(self, parent=None):
        super(ExtendedDateTimeEdit, self).__init__(
            ui="extendedDateTimeEdit",
            parent=parent
        )
        self.parent = parent

        self.dateTimeEdit = self.find(QDateTimeEdit, "dateTimeEdit")

    def set_time(self, time):
        qdatetime = QDateTime.fromString(
            time,
            "yyyy-MM-dd hh:mm:ss"
        )
        self.dateTimeEdit.setDateTime(qdatetime)

    def get_time(self):
        time = self.dateTimeEdit.dateTime().toPyDateTime()
        return time
