class OneDisplayStatistics {
	constructor(apiUrl, deviceId, screenKey) {
		this.apiUrl = apiUrl;
		this.deviceId = deviceId;
		this.screenKey = screenKey;
		this.statistics = {};

		this.initialize();
	}

	initialize() {
		// Restore stored screen and playlist objects if available.
		const storedStatistics = getStoredValue("statisticsObject");
		if (storedStatistics !== null) {
			try {
				this.statistics = JSON.parse(storedStatistics);
			} catch (err) {

			}
		}
	}




	async addStatistics(id, duration) {
		let date = new Date();
		let hour = date.getHours();
		
		let yyyy = date.getFullYear();
		let mm = (date.getMonth() + 1) + '';
		mm = mm.length < 2 ? '0' + mm : mm;
		//mm = mm.padStart(2, '0');
		let dd = (date.getDate()) + '';
		dd = dd.length < 2 ? '0' + dd : dd;
		//dd = dd.padStart(2, '0');
		let today = `${yyyy}-${mm}-${dd}`;

		// Initialize today's statistics if not present.
		if (typeof this.statistics[today] === 'undefined') {
			this.statistics[today] = { sent: false, hours: {} };
		}
		// Initialize hours if not present
		if (typeof this.statistics[today].hours === 'undefined') {
			this.statistics[today].hours = {};
		}
		// Initialize hour in hours if not present
		if (typeof this.statistics[today].hours[hour] === 'undefined') {
			this.statistics[today].hours[hour] = { items: {} };
		}
		// Initialize the specific id if not present.
		if (typeof this.statistics[today].hours[hour].items[id] === 'undefined') {
			this.statistics[today].hours[hour].items[id] = 0;
		}

		// Add the duration and mark as unsent.
		this.statistics[today].hours[hour].items[id] += duration;
		this.statistics[today].sent = false;

		setStoredValue("statisticsObject", JSON.stringify(this.statistics));
	}

	async sendAndPurgeStatistics() {
		try {
			const today = new Date().toISOString().split('T')[0];
			const url = `${this.apiUrl}/statistics/${this.deviceId}${this.screenKey ? `/${this.screenKey}` : ""}`;
			await axios.post(url, { statistics: this.statistics });

			// Only mark as sent after a successful post.
			for (const dateKey of Object.keys(this.statistics)) {
				if (dateKey !== today && this.statistics[dateKey].sent) {
					delete this.statistics[dateKey];
				} else {
					this.statistics[dateKey].sent = true;
				}
			}

			setStoredValue("statisticsObject", JSON.stringify(this.statistics));
		} catch (error) {
			console.error("Error sending statistics:", error);
		}
	}

	async publishStatistics() {
		// Corrected to call sendAndPurgeStatistics.
		await this.sendAndPurgeStatistics();
		setTimeout(() => {
			this.publishStatistics();
		}, 60000);
	}

}
