use crate::world::World;

pub fn follow_system(world: &mut World)
{
    let following_entities: Vec<_> = world.follows.all();

    for entity in following_entities
    {
        if let Some(follow) = world.follows.get(entity)
        {
            let target = follow.target;
            if let Some(target_transform) = world.transforms.get(target)
            {
                let target_pos = target_transform.position;
                let target_rot = target_transform.rotation;
                let target_scale = target_transform.scale;
                let offset = follow.offset;
                let inherit_rot = follow.inherit_rotation;
                let inherit_scale = follow.inherit_scale;

                world.transforms.with_mut(entity, |transform| {
                    transform.position = target_pos;

                    if inherit_rot
                    {
                        let rotated_offset = target_rot * offset.position;
                        transform.position += rotated_offset;
                        transform.rotation = target_rot * offset.rotation;
                    }
                    else
                    {
                        transform.position += offset.position;
                        transform.rotation = offset.rotation;
                    }

                    if inherit_scale
                    {
                        transform.scale = target_scale * offset.scale;
                    }
                    else
                    {
                        transform.scale = offset.scale;
                    }
                });
            }
        }
    }
}
