import time
import math
import pygame

class Animator:
    def __init__(self, target, animation_speed=0.1):
        self.target = target
        self.animation_speed = animation_speed
        self.current_frame = 0
        self.last_update_time = time.time()
        self.base_y = getattr(target, 'y', 0)

    def refresh(self):
        if not hasattr(self.target, 'animations'):
            return
            
        state = self.target.state
        if state not in self.target.animations:
            return

        current_time = time.time()
        
        if current_time - self.last_update_time > self.animation_speed:
            frames = self.target.animations[state]
            self.current_frame = (self.current_frame + 1) % len(frames)
            self.target.image = frames[self.current_frame]
            self.last_update_time = current_time

    def hover(self, amplitude=5, speed=5):
        self.target.y = self.base_y + math.sin(time.time() * speed) * amplitude

    def rotate_loop(self, speed=100):
        angle = (time.time() * speed) % 360
        self.target.image = pygame.transform.rotate(self.target.image, angle)

    def set_speed(self, speed):
        self.animation_speed = speed