# -*- 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.
#
# Authors: Alessandro Decina <alessandro@fluendo.com>

from elisa.core.utils.cancellable_defer import CancellableDeferred
from elisa.core.log import Loggable

class Request(object):
    def __init__(self, metadata):
        self.metadata = metadata
        self.defer = None
        self.cancelled = False

class RequestQueue(Loggable):
    log_category = 'gst_request_queue'

    def __init__(self):
        super(RequestQueue, self).__init__()
        self._requests = []

    def enqueue(self, metadata):
        request = Request(metadata)
        def cancel(dfr):
            request.cancelled = True
        dfr = CancellableDeferred(canceller=cancel)
        request.defer = dfr
        self._requests.append(request)

        return dfr

    def dequeue(self):
        while True:
            request = self._requests.pop(0)

            if request.cancelled:
                self.debug('request %s cancelled' % request.metadata)
                # break the refcount cycle
                request.defer = None
                continue

            return request

    def __len__(self):
        return len(self._requests)

