pub struct Timer {
    duration: f64,
    elapsed: f64,
    repeating: bool,
    finished: bool,
}

impl Timer {
    pub fn once(duration: f64) -> Self {
        Self {
            duration,
            elapsed: 0.0,
            repeating: false,
            finished: false,
        }
    }

    pub fn repeating(duration: f64) -> Self {
        Self {
            duration,
            elapsed: 0.0,
            repeating: true,
            finished: false,
        }
    }

    pub fn tick(&mut self, delta: f64) -> bool {
        if self.finished && !self.repeating {
            return false;
        }

        self.elapsed += delta;

        if self.elapsed >= self.duration {
            self.finished = true;
            if self.repeating {
                self.elapsed -= self.duration;
            }
            return true;
        }

        false
    }

    pub fn reset(&mut self) {
        self.elapsed = 0.0;
        self.finished = false;
    }

    pub fn fraction(&self) -> f64 {
        if self.duration <= 0.0 {
            return 1.0;
        }
        (self.elapsed / self.duration).clamp(0.0, 1.0)
    }

    pub fn elapsed(&self) -> f64 {
        self.elapsed
    }

    pub fn finished(&self) -> bool {
        self.finished
    }

    pub fn duration(&self) -> f64 {
        self.duration
    }

    pub fn set_duration(&mut self, duration: f64) {
        self.duration = duration;
    }
}
