// Create an object to store picture counts for each cameraSource
let pictureCounts = JSON.parse(localStorage.getItem('pictureCounts')) || {};

// Function to reset pictureCounts at midnight
function resetPictureCountsAtMidnight() {
  // const now = new Date();
  // const midnight = new Date(now);
  const midnight = new Date();
  midnight.setHours(24, 0, 0, 0); // Set time to midnight

  const lastResetTime = localStorage.getItem('lastResetTime');
  if (!lastResetTime || new Date(lastResetTime) < now) {
    const timeUntilMidnight = midnight - now;
    // https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
    setTimeout(resetAndReschedule, timeUntilMidnight);
  }
}

// Function to reset pictureCounts, save data, and reschedule
function resetAndReschedule() {
  const now = new Date();
  const today = new Date(now);
  const month = String(today.getMonth() + 1).padStart(2, '0'); // Months are zero-based
  const day = String(today.getDate()).padStart(2, '0');
  const formattedDate = `${month}-${day}`;
  const keyWithDate = `pictureCountsData_${formattedDate}`;

  localStorage.setItem(keyWithDate, JSON.stringify(pictureCounts));
  pictureCounts = {}; // Reset pictureCounts
  localStorage.setItem('lastResetTime', now.toISOString()); // Store the reset time
  localStorage.setItem('pictureCounts', JSON.stringify(pictureCounts)); // Store pictureCounts

  resetPictureCountsAtMidnight(); // Schedule the next reset
}

// Start the initial reset
resetPictureCountsAtMidnight();