birds = {}

function birds:new()
    local bird = {
        max_timer_num   = 0.25,
        anim_speed      = 25,
        timer           = 0,
        sign            = 1,
        main_body       = 0,
        time            = 0,
        max_vel         = 10,
        max_impulse     = 20,
        max_ang_vel     = 15,
        max_ang_impulse = 10,
        joints          = {},
        wings           = {},
        sky_transform   = {},
        body_transform  = {},


        Init = function(self, body, wings, joints, new_sky_transform)
            self.timer          = self.max_timer_num
            self.sky_transform  = new_sky_transform
            self.main_body      = body
            self.body_transform = GetBodyTransform(self.main_body)
            self.wings          = wings
            self.joints         = joints
        end,

        Update = function(self, dt)
            self.body_transform = GetBodyTransform(self.main_body)
            self:PlayAnimation(dt)

            -- ===================================
            -- Fly away with constrain:
            ConstrainPosition(self.main_body, 0, self.body_transform.pos, self.sky_transform.pos, self.max_vel, self.max_impulse)
            local next_rot = QuatLookAt(self.sky_transform.pos, self.body_transform.pos)
            ConstrainOrientation(self.main_body, 0, self.body_transform.rot, next_rot, self.max_ang_vel, self.max_ang_impulse)

        end,

        IsFlewAway = function(self)
            if VecLength(VecSub(self.body_transform.pos, self.sky_transform.pos)) < 10 then
                self:DeleteBird()
                return true
            end
            return false
        end,

        DeleteBird = function(self)
            Delete(self.main_body)

            for i = 1, #self.wings do
                Delete(self.wings[i])
            end

            for i = 1, #self.joints do
                Delete(self.joints[i])
            end
        end,

        SetVelAndImpulse = function(self, max_vel, max_impulse, max_ang_vel, max_ang_impulse)
            self.max_vel = max_vel ~= nil and max_vel or self.max_vel
            self.max_impulse = max_impulse ~= nil and max_impulse or self.max_impulse
            self.max_ang_vel = max_ang_vel ~= nil and max_ang_vel or self.max_ang_vel
            self.max_ang_impulse = max_ang_impulse ~= nil and max_ang_impulse or self.max_ang_impulse
        end,

        PlayAnimation = function(self, dt)
            if self.timer < 0 then
                self.timer = self.max_timer_num
                self.sign = self.sign * (-1)
            else
                self.timer = self.timer - dt
            end

            for i = 1, #self.joints do
                SetJointMotor(self.joints[i], self.anim_speed * self.sign)
            end
        end,
    }

	setmetatable(bird, {__index = self})
	return bird
end
