#include "date_time_generator.h" DateTimeGenerator::DateTimeGenerator(const QPair &dayRange, const QPair &timeRange) : dayRange_(dayRange), timeRange_(timeRange) { auto &[lowestDate, highestDate] = dayRange_; if (lowestDate < 0 || highestDate < 0) { qFatal() << "Lowest or highest date is negative"; } if (lowestDate > highestDate) { qCritical() << "Lowest date is greater than the highest date, values will " "be swapped"; std::swap(lowestDate, highestDate); } auto &[lowestTime, highestTime] = timeRange_; if (!lowestTime.isValid() || !highestTime.isValid()) { qFatal() << "Lowest or highest time is not valid"; } if (lowestTime > highestTime) { qCritical() << "Lowest time is greater than the highest time, values will " "be swapped"; std::swap(lowestTime, highestTime); } } QDateTime DateTimeGenerator::generate(const QDateTime &upperBoundInclusive) { auto [lowestDate, highestDate] = dayRange_; auto [lowestTime, highestTime] = timeRange_; const QDate &maxDateValue = upperBoundInclusive.date(); const qint64 maxTimeValueMs = upperBoundInclusive.time().msecsSinceStartOfDay(); QDate epochDate = QDateTime::fromMSecsSinceEpoch(0).date(); qint64 daysFromEpochDateToMaxDateValue = epochDate.daysTo(maxDateValue); highestDate = std::min(highestDate, daysFromEpochDateToMaxDateValue); qint64 minusDeltaDays = -bounded(lowestDate, highestDate); QDate dateSoldAt = maxDateValue.addDays(minusDeltaDays); qint64 lowestTimeMs = lowestTime.msecsSinceStartOfDay(); qint64 highestTimeMs = highestTime.msecsSinceStartOfDay() + 1; qint64 msecsSinceStartOfDay = bounded(lowestTimeMs, highestTimeMs); if (msecsSinceStartOfDay > maxTimeValueMs) { msecsSinceStartOfDay = maxTimeValueMs; } QTime timeSoldAt = QTime::fromMSecsSinceStartOfDay(msecsSinceStartOfDay); return {std::move(dateSoldAt), std::move(timeSoldAt)}; } QDateTime DateTimeGenerator::generate(const QDateTime &lowerBoundInclusive, const QDateTime &upperBoundInclusive) { if (lowerBoundInclusive > upperBoundInclusive) { qFatal() << "Lower bound date is greater than the upper bound date"; } const QDate &minDateValue = lowerBoundInclusive.date(); const QTime &minTimeValue = lowerBoundInclusive.time(); QDateTime unboundedLower = generate(upperBoundInclusive); QDate boundedDate = unboundedLower.date() <= minDateValue ? minDateValue : unboundedLower.date(); QTime boundedTime = unboundedLower.time() <= minTimeValue ? minTimeValue : unboundedLower.time(); return {std::move(boundedDate), std::move(boundedTime)}; }