# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.
#
# Author: Olivier Tilloy <olivier@fluendo.com>

"""
A standard loading (spinning) animation widget.
"""

from elisa.plugins.pigment.graph.image import Image
from elisa.plugins.pigment.widgets.widget import Widget
from elisa.plugins.pigment.widgets.theme import Theme

import pgm
from elisa.plugins.pigment.animation.implicit import AnimatedObject

import math


class LoadingAnimation(Widget):

    """
    A standard loading (spinning) animation widget.
    """

    def __init__(self, duration=950,
                 resource='elisa.plugins.poblesec.loading'):
        """
        Constructor.

        @param duration: the duration of one cycle of the animation, in
                         milliseconds
        @type duration:  C{int}
        @param resource: the theme image resource to use as an animation
        @type resource:  C{str}
        """
        super(LoadingAnimation, self).__init__()

        self._duration = duration

        theme = Theme.get_default()

        self._image = Image()
        self.add(self._image)
        image_file = theme.get_resource(resource)
        self._image.set_from_file(image_file)
        self._image.position = (0.0, 0.0, 0.0)
        self._image.size = (1.0, 1.0)
        self._image.bg_a = 0
        self._image.visible = True

        self._animated_image = AnimatedObject(self._image, ('rz',))

    def activate(self, active):
        """
        Start/stop the animation.
        This does not change the visibility of the widget.

        @param active: whether to start or stop the animation
        @type active:  C{bool}
        """
        if active:
            self._animated_image.setup_next_animations('rz',
                                                       repeat_count=-1, # INFINITE
                                                       duration=self._duration)
            self._image.rz = 0.0
            self._animated_image.rz = math.pi * 2
        else:
            self._animated_image.stop_animations()

    def clean(self):
        self._animated_image.stop_animations()
        self._animated_image = None
        self._image.clean()
        self._image = None
        return super(LoadingAnimation, self).clean()
