from PyQt6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QHBoxLayout, QListWidget,
    QPushButton, QLabel, QDateEdit, QListWidgetItem
)
from PyQt6.QtCore import QDate
import sys

class AverageDateCalculator(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Среднее значение дат")
        self.resize(400, 300)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # Список дат
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
        self.layout.addWidget(self.list_widget)

        # Кнопки для добавления/удаления
        btn_layout = QHBoxLayout()
        self.add_btn = QPushButton("Добавить сегодня")
        self.remove_btn = QPushButton("Удалить выбранные")
        btn_layout.addWidget(self.add_btn)
        btn_layout.addWidget(self.remove_btn)
        self.layout.addLayout(btn_layout)

        # Диапазон дат
        range_layout = QHBoxLayout()
        self.start_date = QDateEdit()
        self.end_date = QDateEdit()
        self.start_date.setCalendarPopup(True)
        self.end_date.setCalendarPopup(True)
        self.start_date.setDate(QDate.currentDate())
        self.end_date.setDate(QDate.currentDate())
        range_layout.addWidget(QLabel("С:"))
        range_layout.addWidget(self.start_date)
        range_layout.addWidget(QLabel("По:"))
        range_layout.addWidget(self.end_date)
        self.layout.addLayout(range_layout)

        # Вывод среднего
        self.result_label = QLabel("Среднее: —")
        self.layout.addWidget(self.result_label)

        # Сигналы
        self.add_btn.clicked.connect(self.add_today)
        self.remove_btn.clicked.connect(self.remove_selected)
        self.list_widget.itemSelectionChanged.connect(self.compute_average)
        self.start_date.dateChanged.connect(self.compute_average)
        self.end_date.dateChanged.connect(self.compute_average)

    def add_today(self):
        today = QDate.currentDate()
        item = QListWidgetItem(today.toString("yyyy-MM-dd"))
        self.list_widget.addItem(item)
        self.compute_average()

    def remove_selected(self):
        for item in self.list_widget.selectedItems():
            self.list_widget.takeItem(self.list_widget.row(item))
        self.compute_average()

    def compute_average(self):
        # Собираем даты
        selected_items = self.list_widget.selectedItems()
        if selected_items:
            dates = [QDate.fromString(item.text(), "yyyy-MM-dd") for item in selected_items]
        else:
            # Если ничего не выделено, берем все элементы в диапазоне
            start = self.start_date.date()
            end = self.end_date.date()
            dates = []
            for i in range(self.list_widget.count()):
                date = QDate.fromString(self.list_widget.item(i).text(), "yyyy-MM-dd")
                if start <= date <= end:
                    dates.append(date)

        if not dates:
            self.result_label.setText("Среднее: —")
            return

        # Вычисляем среднее
        days_sum = sum([date.toJulianDay() for date in dates])
        avg_day = days_sum // len(dates)
        avg_date = QDate.fromJulianDay(avg_day)
        self.result_label.setText(f"Среднее: {avg_date.toString('yyyy-MM-dd')}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AverageDateCalculator()
    window.show()
    sys.exit(app.exec())