# -*- 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: Fernando Casanova <fcasanova@fluendo.com>

from twisted.trial.unittest import TestCase, SkipTest

from elisa.core.media_uri import MediaUri
from elisa.core.utils import defer
from elisa.core.utils.misc import run_functional_tests_check

from elisa.plugins.lastfm.resource_provider import IMG_SERVER,\
                                                   get_lastfm_albumgetinfo_url,\
                                                   LastFMResourceProvider
from elisa.plugins.lastfm.models import LastFMAlbumModel

from elisa.plugins.base.models.audio import ArtistModel
from elisa.plugins.base.models.media import RawDataModel

import binascii


class TestLastFMResource(TestCase):

    def setUp(self):
        def created(resource):
            self.resource = resource

        return LastFMResourceProvider.create({}).addCallback(created)

    def tearDown(self):
        return self.resource.clean()

    def test_simple_parsing(self):
        """
        test for parsing some simple code
        """
        data = """<lfm status="ok"><album><name>Greatest Hits</name><artist>Queen</artist><id>1831</id><mbid>84213105-f89d-4243-9b71-c27f1d17598c</mbid><url>http://www.last.fm/music/Queen/Greatest+Hits</url><releasedate>    3 Oct 1994, 00:00</releasedate><image size="small">http://userserve-ak.last.fm/serve/34s/12618651.jpg</image><image size="medium">http://userserve-ak.last.fm/serve/64s/12618651.jpg</image><image size="large">http://userserve-ak.last.fm/serve/174s/12618651.jpg</image><image size="extralarge">http://userserve-ak.last.fm/serve/300x300/12618651.jpg</image><listeners>680916</listeners><playcount>6737804</playcount><toptags><tag><name>classic rock</name><url>http://www.last.fm/tag/classic%20rock</url></tag><tag><name>queen</name><url>http://www.last.fm/tag/queen</url></tag><tag><name>albums i own</name><url>http://www.last.fm/tag/albums%20i%20own</url></tag><tag><name>rock</name><url>http://www.last.fm/tag/rock</url></tag><tag><name>80s</name><url>http://www.last.fm/tag/80s</url></tag></toptags><wiki><published>Thu, 19 Mar 2009 17:17:11 +0000</published><summary>Greatest Hits is a compilation album by the British rock band Queen. The record, released on November 2, 1981, is the UK's all-time best-selling album. Combined with Greatest Hits II, it became the definitive Queen compilation. While a domestic release with different tracks but the same cover art was available in the U.S. in 1981, the British release was available to United States customers only by import until the 1995 release of Greatest Hits I &amp; II, which combined the two discs. The seventeen-track UK Greatest Hits disc was released in the U.</summary><content>Greatest Hits is a compilation album by the British rock band Queen. The record, released on November 2, 1981, is the UK's all-time best-selling album. Combined with Greatest Hits II, it became the definitive Queen compilation. While a domestic release with different tracks but the same cover art was available in the U.S. in 1981, the British release was available to United States customers only by import until the 1995 release of Greatest Hits I &amp; II, which combined the two discs. The seventeen-track UK Greatest Hits disc was released in the U.S. on its own for the first time, with a few bonus tracks, in 2004 under the name Greatest Hits: We Will Rock You Edition.</content></wiki></album></lfm>"""

        model = LastFMAlbumModel()
        result = self.resource._response_read(data, model, 'http://fake.url')
        self.assertEquals(model.id, '1831')
        self.assertEquals(len(model.cover.references), 1)
        c = model.cover
        self.assertTrue(isinstance(c.references[0], MediaUri))
        self.assertEquals(str(c.references[-1]), 'http://userserve-ak.last.fm/serve/300x300/12618651.jpg')


class TestLastFMResourceProviderFunctional(TestCase):

    """
    Functional tests for the LastFM resource provider.
    Requires an internet connection.
    """

    def setUp(self):
        run_functional_tests_check()

        def created(provider):
            self.provider = provider

        dfr = LastFMResourceProvider.create({})
        dfr.addCallback(created)
        return dfr

    def tearDown(self):
        return self.provider.clean()

    def test_get_id(self):
        album_name = 'Els millors professors europeus'
        artist = 'Manel'
        url = get_lastfm_albumgetinfo_url(artist, album_name)
        model, dfr = self.provider.get(url)

        def got_response(model):
            self.failUnless(isinstance(model, LastFMAlbumModel))
            self.failUnlessEqual(model.id, '23176942')
            self.failIfEqual(model.cover, None)

        dfr.addCallback(got_response)
        return dfr

    def test_get_image(self):
        url = 'http://%s/serve/300x300/8596783.jpg' % IMG_SERVER
        image_size = 81715
        model, dfr = self.provider.get(url)

        def got_response(model):
            self.failUnless(isinstance(model, RawDataModel))
            self.failUnlessEqual(model.size, image_size)
            header = 'ffd8' + 'ffe0' # SOI marker + JFIF marker
            self.failUnlessEqual(binascii.hexlify(model.data[:4]), header)

        dfr.addCallback(got_response)
        return dfr

    def test_error_noartist(self):
        album_name = 'Hooray for Boobies'
        artist = ''
        url = get_lastfm_albumgetinfo_url(artist, album_name)
        model, dfr = self.provider.get(url)
        self.failUnlessFailure(dfr, ValueError)
        return dfr
