package com.ffii.fpsms.modules.monitoring.scheduler

import com.ffii.fpsms.modules.monitoring.service.LabelPrinterMonitorService
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component

@Component
@ConditionalOnProperty(prefix = "fpsms.monitoring", name = ["enabled"], havingValue = "true")
class LabelPrinterMonitorScheduler(
    private val labelPrinterMonitorService: LabelPrinterMonitorService,
) {
    private val log = LoggerFactory.getLogger(LabelPrinterMonitorScheduler::class.java)

    @Scheduled(fixedRateString = "\${fpsms.label-printer-monitor.check-interval-ms:120000}")
    fun scanLabelPrinters() {
        try {
            val result = labelPrinterMonitorService.checkAllLabelPrinters()
            @Suppress("UNCHECKED_CAST")
            val summary = result["summary"] as? Map<String, Any>
            val offline = summary?.get("offline") ?: 0
            if ((offline as? Number)?.toInt()?.let { it > 0 } == true) {
                log.warn("Label printer monitor: {} label printer(s) offline", offline)
            }
        } catch (e: Exception) {
            log.error("Label printer connectivity / odometer scan failed", e)
        }
    }
}
