# -*- 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: Guido Amoruso <guidonte@fluendo.com>


from elisa.plugins.poblesec.widgets.sliced_image import SlicedImageHorizontal
from elisa.plugins.pigment.widgets.widget import Widget
from elisa.plugins.pigment.graph.image import Image
from elisa.plugins.pigment.widgets.theme import Theme
from elisa.plugins.pigment.widgets.const import *

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

import gobject

import logging


class BufferingBar(Widget):
    """
    Buffering bar displaying a continuous animation.
    """

    def __init__(self):
        super(BufferingBar, self).__init__()

        self._padding_horizontal = 0.01
        self._padding_vertical = 0.1

        theme = Theme.get_default()

        bg = SlicedImageHorizontal()
        self.add(bg)
        self._background = bg
        bg.visible = True

        img = Image()
        resource = theme.get_resource('elisa.plugins.poblesec.player.buffering.segment')
        img.set_from_file(resource)
        img.bg_color = (255, 255, 255, 0)
        img.wrapping = (pgm.IMAGE_REPEAT, pgm.IMAGE_REPEAT)
        img.layout = pgm.IMAGE_FILLED
        self.add(img)
        self._image = img
        img.visible = True

        self._img = img
        self._animated_img = AnimatedObject(self._img,
                                                     ('mapping_tx',))

        self.update_style_properties(self.style.get_items())

        self._resized_signal_id = self.connect("resized", self._set_size)

    def update_style_properties(self, props=None):
        if props is None:
            return

        remaining_props = {}

        theme = Theme.get_default()
        pending_resize = False

        for key, value in props.iteritems():
            if key == 'left-cap':
                resource = theme.get_resource("elisa.plugins.poblesec.progress_bar_left_cap")
                self._background.left_cap.set_from_file(resource)
            elif key == 'body':
                resource = theme.get_resource("elisa.plugins.poblesec.progress_bar_body")
                self._background.body.set_from_file(resource)
            elif key == 'right-cap':
                resource = theme.get_resource("elisa.plugins.poblesec.progress_bar_right_cap")
                self._background.right_cap.set_from_file(resource)
            elif key == 'padding-horizontal':
                self._padding_horizontal = value
                self._image.width = 1.0 - self._padding_horizontal * 2
                self._image.x = self._padding_horizontal
                pending_resize = True
            elif key == 'padding-vertical':
                self._padding_vertical = value
                self._image.height = 1.0 - self._padding_vertical * 2
                self._image.y = self._padding_vertical
                pending_resize = True
            else:
                remaining_props[key] = value

        if pending_resize:
            self._set_size(None, None, None)

        if len(remaining_props) > 0:
            return super(BufferingBar, self).update_style_properties(remaining_props)

    def clean(self):
        if self._resized_signal_id is not None:
            self.disconnect(self._resized_signal_id)
        self._resized_signal_id = None

    def start_animation(self):
        """
        Start the animation.

        Note that the x-transltion of the mapping matrix is reset.
        """

        self._animated_img.setup_next_animations(repeat_count=-1, # INFINITE
                                                 duration=300)
        self._img.mapping_tx = 0.0
        self._animated_img.mapping_tx = -1.0

    def stop_animation(self):
        """Stop the animation."""

        self._animated_img.stop_animations()

    def _set_size(self, widget, width, height):
        w = self.absolute_width * (1.0 - self._padding_horizontal * 2)
        h = self.absolute_height * (1.0 - self._padding_vertical * 2)
        self._img.mapping_sx = w / h


if __name__ == "__main__":
    import logging

    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    Theme.set_default(Theme.load_from_module('elisa.plugins.poblesec'))

    buffering_bar = BufferingBar.demo ()
    buffering_bar.size = (2.0, 0.1)
    buffering_bar.start_animation()

    try:
        __IPYTHON__
    except NameError:
        pgm.main()

