#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Sascha Steinbiss <sascha@steinbiss.name>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# On Debian Systems you can find a copy of the text of GPL version 3
# at /usr/share/common-licenses/GPL-3.

import gi
gi.require_version('Atspi', '2.0')
gi.require_version('Wnck', '3.0')
import dogtail
import dogtail.utils
import dogtail.procedural
import os
import stem
import stem.connection
import unittest


class TestOnionCircuitsGUI(unittest.TestCase):

    def setUp(self):
        os.environ["LC_ALL"] = 'C'
        self.pid = dogtail.utils.run('onioncircuits')
        self.rootapp = dogtail.tree.root.application('onioncircuits')
        self.window_title = 'Onion Circuits'
        dogtail.procedural.focus.application("onioncircuits")
        dogtail.procedural.focus.frame(self.window_title)

    def _get_circuits(self):
        circs = set()
        with stem.connection.connect_socket_file() as controller:
            controller.authenticate()
            for circ in sorted(controller.get_circuits()):
                if circ.status != stem.CircStatus.BUILT:
                    continue
                nicks = []
                for i, entry in enumerate(circ.path):
                    fingerprint, nickname = entry
                    nicks.append(nickname)
                circs.add(", ".join(nicks))
        return circs

    def test_has_correct_circuits(self):
        children = self.rootapp.findChildren(
            dogtail.predicate.GenericPredicate(roleName='table cell'))
        lastcell = None
        mycircs = set()
        for child in children:
            if child.text is not None:
                if lastcell is not None:
                    if child.text == 'Built':
                        mycircs.add(lastcell)
                lastcell = child.text

        self.assertTrue(len(mycircs) > 0)
        self.assertEqual(self._get_circuits(), mycircs)


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