//
//  TSCustomTimer.swift
//  Girly
//
//  Created by 100Years on 2025/1/9.
//

import Foundation

class TSCustomTimer {
    private var timer: Timer?
    private var interval: TimeInterval
    private var repeats: Bool
    private var action: (() -> Void)?
    
    /// 初始化定时器
    /// - Parameters:
    ///   - interval: 时间间隔（单位：秒）
    ///   - repeats: 是否重复
    ///   - action: 定时器触发时执行的闭包
    init(interval: TimeInterval, repeats: Bool, action: @escaping () -> Void) {
        self.interval = interval
        self.repeats = repeats
        self.action = action
    }
    
    /// 开启定时器
    func start() {
        // 确保不会重复创建定时器
        stop()
        timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: repeats) { [weak self] _ in
            self?.action?()
        }
        // 将定时器加入运行循环
        RunLoop.current.add(timer!, forMode: .common)
    }
    
    /// 停止定时器
    func stop() {
        timer?.invalidate()
        timer = nil
    }
    
    /// 销毁定时器
    func destroy() {
        stop()
        action = nil
    }
}
