#! /usr/bin/python3
# -*- coding: utf-8 -*-
from gi.repository import Unity
from unittest import TestCase
import imp

class ResultSet(Unity.ResultSet):
    def __init__(self):
        Unity.ResultSet.__init__(self)
        self.results = []

    def do_add_result(self, result):
        self.results.append({'uri':result.uri,
                             'title':result.title,
                             'comment':result.comment,
                             'icon':result.icon_hint})


class ScopeTestCase(TestCase):
    def init_scope(self, scope_path):
        self.scope_module = imp.load_source('scope', scope_path)
        self.scope = self.scope_module.load_scope()

    def perform_query(self, query, filter_set=None, cancellable=None):
        if filter_set is None:
            filter_set = Unity.FilterSet.new()
        if cancellable is None:
            cancellable = Unity.Cancellable.create()
        result_set = ResultSet()
        ctx = Unity.SearchContext.create(
            query, 0, filter_set, None, result_set, cancellable)
        s = self.scope.create_search_for_query(ctx)
        s.run()
        return result_set


class TestGithub(ScopeTestCase):
    def setUp(self):
        self.init_scope('src/unity_github_daemon.py')

    def tearDown(self):
        self.scope = None
        self.scope_module = None

    def test_repo_searches(self):
        self.scope_module.SEARCH_URI = 'file:tests/data/mock_github_repo_pass#'
        result_set = self.perform_query('ubuntu')
        self.assertEqual(len(result_set.results), 25)
        result = result_set.results[0]
        self.assertEqual(
            result['uri'], 'https://github.com/tualatrix/ubuntu-tweak')
        self.assertEqual(result['icon'], '. GThemedIcon text-x-python gnome-mime-text-x-python text-x-generic')
        self.assertEqual(result['title'], 'ubuntu-tweak')
        self.assertEqual(result['comment'], 'Ubuntu Tweak is a tool that '
                         'makes it easy to configure your system and '
                         'desktop settings. ')

    def test_failing_search(self):
        self.scope_module.SEARCH_URI = 'file:tests/data/mock_github_fail#'
        result_set = self.perform_query('didrocks')
        self.assertEqual(len(result_set.results), 0)

    def test_cancelled_search(self):
        self.scope_module.SEARCH_URI = 'file:tests/data/mock_github_repo_pass#'
        cancellable = Unity.Cancellable.create()
        cancellable.cancel()
        result_set = self.perform_query("whatever", cancellable=cancellable)
        self.assertEqual(result_set.results, [])


if __name__ == '__main__':
    unittest.main()
