# 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.

from elisa.core.tests.test_media_provider import TestMediaProvider
from elisa.core import db_backend
from elisa.core.media_uri import MediaUri
from elisa.core import plugin
import os, platform
from twisted.internet import defer
import tempfile

from twisted.trial.unittest import SkipTest

from elisa.plugins.base.messages.foreign_application_message import ForeignApplicationMessage

class BasePlugin(plugin.Plugin):
    name = 'base'
    components = {'foreign_application_message':
                  {'path': ForeignApplicationMessage}
                  }

class FspotTest(TestMediaProvider):
    component_class = 'fspot_media:FspotMedia'
    component_path = '..'
    dump_path = None

    def __init__(self, methodName='runTests'):
        TestMediaProvider.__init__(self, methodName)
        if self.dump_path is None:
            self.skip = "no db dump to load"
        if platform.system() == 'Windows':
            self.skip = "test not supported under windows"
    
    def setUp(self):
        self._boot()
        from elisa.core import common
        plugin_registry = common.application.plugin_registry
        
        plugin_registry.register_plugin(BasePlugin)

        # load the SQL dump
        dump_path = os.path.join(self.directory, self.dump_path)
        fd, self._db_path = tempfile.mkstemp()

        db = db_backend.DBBackend(db_backend='sqlite',
                                  database=self._db_path)
        for statement in open(dump_path).read().split(';'):
            db.sql_execute(statement)
        db.save_changes()
        db.disconnect()

        self.config = {'db_path': self._db_path}

        dfr = TestMediaProvider.setUp(self)
        return dfr

    def get_valid_uris(self):
        return [MediaUri("fspot:///")]

    def tearDown(self):
        TestMediaProvider.tearDown(self)
        os.unlink(self._db_path)
    
class TestKaleoFspot(FspotTest):

    dump_path = 'data/kaleo.sql'




class TestFspotMedia0_3(FspotTest):

    dump_path = 'data/fspot_0_3.sql'


    def test_get_media_type(self):

        def check_file(result):
            self.assertEquals(result['file_type'], 'image')
            self.assertEquals(result['mime_type'], 'image/jpeg')

        u1 = MediaUri(u'fspot:///home/phil/Photos/2003/1/29/hippo.jpg?tag_id=3#20')
        d1 = self.component.get_media_type(u1)
        d1.addCallback(check_file)

        def check_dir(result):
            self.assertEquals(result['file_type'], 'directory')
            self.assertEquals(result['mime_type'], '')
            
        u2 = MediaUri(u'fspot:///tmp?id=6&tag_id=3')
        d2 = self.component.get_media_type(u2)
        d2.addCallback(check_dir)

        d = defer.DeferredList([d1,d2])
        return d
        
    def test_has_children(self):

        def check_file(result):
            self.assertEquals(result, False)

        u1 = MediaUri(u'fspot:///home/phil/Photos/2003/1/29/hippo.jpg?tag_id=3#20')
        d1 = self.component.has_children_with_types(u1,['image',])
        d1.addCallback(check_file)

        def check_dir(result):
            self.assertEquals(result, True)
      
        u2 = MediaUri(u'fspot:///tmp/?id=6&tag_id=3')
        d2 = self.component.has_children_with_types(u2, ['image',])
        d2.addCallback(check_dir)

        def check_dir2(result):
            self.assertEquals(result, True)
      
        u3 = MediaUri(u'fspot:///')
        d3 = self.component.has_children_with_types(u3, ['directory',])
        d3.addCallback(check_dir2)

        u4 = MediaUri("fspot:///subtmp?id=7&tag_id=6")
        d4 = self.component.has_children_with_types(u4, ['directory', 'image'])
        d4.addCallback(check_dir2)

        d = defer.DeferredList([d1,d2,d3,d4])
        return d

    def test_get_direct_children(self):

        def got_children(children):
            expected = ['fspot:///Events?id=5&tag_id=-1',
                        'fspot:///Favorites?id=1&tag_id=-1',
                        'fspot:///Hidden?id=2&tag_id=-1',
                        'fspot:///People?id=3&tag_id=-1',
                        'fspot:///Places?id=4&tag_id=-1']
            children = [ str(uri) for uri, metadata in children ]
            self.assertEquals(expected, children)
        raise SkipTest("skip test because of translation problems")
        d1 = self.component.get_direct_children(MediaUri('fspot:///'),
                                                [])
        d1.addCallback(got_children)
        return d1
    
    def test_get_direct_children_tmp(self):

        def got_children(children):
            expected = ['fspot:///home/phil/Photos/2001/2/17/duck.jpg?tag_id=7#19',
                        'fspot:///home/phil/Photos/2001/9/26/dogs.jpg?tag_id=7#18',
                        'fspot:///home/phil/Photos/2002/4/1/lambs.jpg?tag_id=7#22',
                        'fspot:///Hidden?id=2&tag_id=7']
            children = [ str(uri) for uri, metadata in children ]
            self.assertEquals(expected, children)

        d1 = self.component.get_direct_children(MediaUri("fspot:///subtmp?id=7&tag_id=6"),
                                                [])
        d1.addCallback(got_children)
        return d1

class TestFspotMedia0_4(TestFspotMedia0_3):

    dump_path = 'data/fspot_0_4.sql'
