#!/usr/bin/python

from mooix import *
import os, time

if this.spring.int:
    # Set the duck to waddling. Note that this is done while
    # the duck is still (presumably) locked by the caller. Use
    # a unique id in the waddling field since this method might
    # be called twice at the same time.
    my_id = os.getpid()
    this.waddling = my_id

    # After forking to the background, the duck isn't locked
    # for movement anymore (since the caller holds the lock
    # only until this method returns).
    if background():
        # Waddle around a bit, depending on how tightly the spring
        # is wound.
        spring = this.spring.int
        max_spring = this.max_spring.int
        while spring > (max_spring / 2.0):
            # Lock the duck for movement, then check to see if
            # it's still supposed to be waddling, or if
            # something stopped it.
            lock = this.getlock()
            if this.waddling.int == my_id:
                # The duck is still waddling.
                this.msg('energetic_waddle')
                spring -= 1;
                lock.close()  # allow someone to intercept it
                time.sleep(1) # while it sleeps
            else:
                # Something stopped the waddling.
                this.Return()
        # A final waddle, and stop waddling.
        lock = this.getlock()
        if this.waddling.int == my_id:
            this.msg('waddle')
            this.waddling = 0
            # Unwind the spring all the way.
            this.spring = 0
            lock.close()
        else:
            this.Return();
    else:
        this.Return() # failure
