File indexing completed on 2024-11-24 04:50:39

0001 // SPDX-FileCopyrightText: 2023 Carl Schwan <carl@carlschwan.eu>
0002 // SPDX-License-Identifier: LGPL-2.0-or-later
0003 
0004 #include "datetimestate.h"
0005 #include <QTimer>
0006 
0007 using namespace std::chrono_literals;
0008 
0009 DateTimeState::DateTimeState(QObject *parent)
0010     : QObject(parent)
0011     , m_selectedDate(QDateTime::currentDateTime())
0012     , m_currentDate(QDateTime::currentDateTime())
0013 {
0014     auto timer = new QTimer(this);
0015     connect(timer, &QTimer::timeout, this, [this, timer] {
0016         m_currentDate = QDateTime::currentDateTime();
0017         Q_EMIT currentDateChanged();
0018 
0019         // Repeat timer
0020         timer->start(60 * 1000ms);
0021     });
0022     timer->start(60 * 1000ms);
0023 }
0024 
0025 void DateTimeState::selectPreviousMonth()
0026 {
0027     m_selectedDate = m_selectedDate.addMonths(-1);
0028     Q_EMIT selectedDateChanged();
0029 }
0030 
0031 void DateTimeState::selectNextMonth()
0032 {
0033     m_selectedDate = m_selectedDate.addMonths(1);
0034     Q_EMIT selectedDateChanged();
0035 }
0036 
0037 bool DateTimeState::isToday(const QDate &date) const
0038 {
0039     return m_currentDate.date() == date;
0040 }
0041 
0042 void DateTimeState::addDays(const int days)
0043 {
0044     m_selectedDate = m_selectedDate.addDays(days);
0045     Q_EMIT selectedDateChanged();
0046 }
0047 
0048 QDateTime DateTimeState::firstDayOfMonth() const
0049 {
0050     QDateTime date = m_selectedDate;
0051     date.setDate(QDate(m_selectedDate.date().year(), m_selectedDate.date().month(), 1));
0052     return date;
0053 }
0054 
0055 QDateTime DateTimeState::firstDayOfWeek() const
0056 {
0057     int dayOfWeek = m_selectedDate.date().dayOfWeek();
0058     return m_selectedDate.addDays(-dayOfWeek + 1);
0059 }
0060 
0061 void DateTimeState::resetTime()
0062 {
0063     m_selectedDate = QDateTime::currentDateTime();
0064     Q_EMIT selectedDateChanged();
0065 }
0066 
0067 void DateTimeState::setSelectedYearMonthDay(const int year, const int month, const int day)
0068 {
0069     m_selectedDate.setDate(QDate(year, month, day));
0070     Q_EMIT selectedDateChanged();
0071 }
0072 
0073 void DateTimeState::setSelectedDay(const int day)
0074 {
0075     setSelectedYearMonthDay(m_selectedDate.date().year(), m_selectedDate.date().month(), day);
0076 }
0077 
0078 void DateTimeState::setSelectedMonth(const int month)
0079 {
0080     setSelectedYearMonthDay(m_selectedDate.date().year(), month, m_selectedDate.date().day());
0081 }
0082 
0083 void DateTimeState::setSelectedYear(const int year)
0084 {
0085     setSelectedYearMonthDay(year, m_selectedDate.date().month(), m_selectedDate.date().day());
0086 }
0087 
0088 #include "moc_datetimestate.cpp"