// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

package client

import (
	
	
)

// PeriodicTimerTimeoutHandler is a handler called on timeout.
type PeriodicTimerTimeoutHandler func(timerID int)

// PeriodicTimer is a periodic timer.
type PeriodicTimer struct {
	id             int
	interval       time.Duration
	timeoutHandler PeriodicTimerTimeoutHandler
	stopFunc       func()
	mutex          sync.RWMutex
}

// NewPeriodicTimer create a new timer.
func ( int,  PeriodicTimerTimeoutHandler,  time.Duration) *PeriodicTimer {
	return &PeriodicTimer{
		id:             ,
		interval:       ,
		timeoutHandler: ,
	}
}

// Start starts the timer.
func ( *PeriodicTimer) () bool {
	.mutex.Lock()
	defer .mutex.Unlock()

	// This is a noop if the timer is always running
	if .stopFunc != nil {
		return false
	}

	 := make(chan struct{})

	go func() {
		 := false

		for ! {
			 := time.NewTimer(.interval)

			select {
			case <-.C:
				.timeoutHandler(.id)
			case <-:
				 = true
				.Stop()
			}
		}
	}()

	.stopFunc = func() {
		close()
	}

	return true
}

// Stop stops the timer.
func ( *PeriodicTimer) () {
	.mutex.Lock()
	defer .mutex.Unlock()

	if .stopFunc != nil {
		.stopFunc()
		.stopFunc = nil
	}
}

// IsRunning tests if the timer is running.
// Debug purpose only.
func ( *PeriodicTimer) () bool {
	.mutex.RLock()
	defer .mutex.RUnlock()

	return (.stopFunc != nil)
}