# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 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 Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.


__maintainer__ = 'Lionel Martin <lionel@fluendo.com>'


from elisa.base_components.action import Action
from elisa.core import player, common
import time

class EnqueueAction(Action):
    """
    DOCME
    """

    label = 'enqueue'
    supported_file_types = ('audio', 'video')

    # Attribute to set at initialization
    # MediaURI instance
    uri = None
    # position to add the uri in playlist
    # -1 : add at the end.
    position = -1
    # listmodel instance
    player_model = None

    # Options:
    # if True, the playlist will be played after uri adding from the begining
    play_now = True
    # if True, the playlist will be removed before adding the new uri
    erase_before_enqueue = True

    # media_types supported by the media activity which creates this action
    media_types = []

    def __call__(self, controller, origin):
        playlist_model = self.player_model.playlist
        playlist_activity = playlist_model.activity
        playlist_activity.media_types = self.media_types

        if playlist_activity.loading:
            self.warning("Already loading the playlist...")
            return
        
        if self.erase_before_enqueue:
            playlist_activity.empty()

        playlist_activity.add_uri(self.uri, -1)

        if self.play_now==True:

            def got_media_type(media_type, model):
                self.player_model.media_type = media_type['file_type']
                uri = model[0]
                self.player_model.uri = uri
                self.player_model.state = player.STATES.PLAYING

            def play_now(model):
                dfr = None
                if len(model):
                    uri = model[0]
                    media_manager = common.application.media_manager
                    dfr = media_manager.get_media_type(uri)
                    dfr.addCallback(got_media_type, model)
                return dfr
                              
            # load items in the playlist
            dfr = playlist_activity.loadmore(self.uri, playlist_model)
            dfr.addCallback(play_now)
