package logger

import (
	"sync"
	"time"
)

type Monitor struct {
	eventLogger    *EventLogger
	lastWrite      time.Time
	mu             sync.RWMutex
	silence5Min    time.Duration
	silence10Min   time.Duration
	watchdogInterval time.Duration
}

func NewMonitor(eventLogger *EventLogger, config *Config) *Monitor {
	m := &Monitor{
		eventLogger:      eventLogger,
		lastWrite:        time.Now(),
		silence5Min:      config.Silence5Min,
		silence10Min:     config.Silence10Min,
		watchdogInterval: config.WatchdogIntervalMin,
	}
	go m.watchdogLoop()
	return m
}

// SetSilenceThresholds позволяет изменить пороги тишины после создания
func (m *Monitor) SetSilenceThresholds(silence5Min, silence10Min time.Duration) {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.silence5Min = silence5Min
	m.silence10Min = silence10Min
}

func (m *Monitor) RecordWrite() {
	m.mu.Lock()
	m.lastWrite = time.Now()
	m.mu.Unlock()
}

func (m *Monitor) watchdogLoop() {
	ticker := time.NewTicker(m.watchdogInterval)
	defer ticker.Stop()

	for range ticker.C {
		m.mu.RLock()
		silence := time.Since(m.lastWrite)
		silence5Min := m.silence5Min
		silence10Min := m.silence10Min
		m.mu.RUnlock()

		if silence > silence10Min {
			m.eventLogger.Event("ТИШИНА_10МИН")
		} else if silence > silence5Min {
			m.eventLogger.Event("ТИШИНА_5МИН")
		}
	}
}