//
//  EnumDebouncer.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 02/06/25.
//

import Foundation

class EnumDebouncer<T: Equatable> {
    private var storedValue: T?
    private var startTime: Date?
    private var timer: Timer?
    private let debounceInterval: TimeInterval = 5 * 60 // 1 hour

    var onDebounceSuccess: ((T) -> Void)?

    func update(with newValue: T) {
        if storedValue == nil || storedValue != newValue {
            reset(newValue: newValue)
            onDebounceSuccess?(newValue)
        } else if let startTime = startTime {
            let elapsed = Date().timeIntervalSince(startTime)
            if elapsed >= debounceInterval {
                triggerSuccess()
            }
        }
    }

    private func reset(newValue: T) {
        storedValue = newValue
        startTime = Date()
        timer?.invalidate()

        timer = Timer.scheduledTimer(withTimeInterval: debounceInterval, repeats: false) { [weak self] _ in
            self?.triggerSuccess()
        }
    }
    
    private func triggerSuccess() {
        guard let value = storedValue else { return }
        
        onDebounceSuccess?(value)
        
        // Do NOT reset storedValue — just reset timer and startTime to keep watching
        startTime = Date()
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: debounceInterval, repeats: false) { [weak self] _ in
            self?.triggerSuccess()
        }
    }
   
    deinit {
        timer?.invalidate()
    }
}
