# -*- 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: Philippe Normand <philippe@fluendo.com>

"""
Dude, my sole purpose is to download Elisa Windows installers.
"""

from twisted.web2.stream import BufferedStream
from twisted.internet import defer

from elisa.core.media_uri import MediaUri
from elisa.core.components.resource_provider import ResourceProvider
from elisa.plugins.base.models.media import RawDataModel
from elisa.plugins.http_client.http_client import ElisaAdvancedHttpClient

class UpdaterResourceProvider(ResourceProvider):
    base_url = "www.moovida.com"
    supported_uri = "http://%s/.*" % base_url

    def __init__(self):
        super(UpdaterResourceProvider, self).__init__()
        base_url = self.base_url
        server_uri = MediaUri('http://%s' % base_url)
        port = server_uri.port or 80
        self._client = ElisaAdvancedHttpClient(host=server_uri.host,
                                               port=port)

    def clean(self):
        if not self._client._closed:
            dfr = self._client.close()
        else:
            dfr = defer.succeed(None)

        def parent_clean(result):
            return super(UpdaterResourceProvider, self).clean()

        dfr.addCallback(parent_clean)
        return dfr

    def get(self, uri, context_model=None):
        """
        Download an installer and store its data in a L{RawDataModel}.
        L{context_model} parameter is not used.
        """
        model = RawDataModel()

        def got_data(data):
            model.data = data
            model.size = len(data)
            return model

        dfr = self._client.request(uri)
        dfr.addCallback(lambda response: BufferedStream(response.stream).readExactly())
        dfr.addCallback(got_data)

        return (model, dfr)
