#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2016, 2019, Sascha Steinbiss <satta@debian.org>
#
# 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_stem_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 _, entry in enumerate(circ.path):
                    _, nickname = entry
                    nicks.append(nickname)
                circs.add(", ".join(nicks))
        return circs

    def _get_gui_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
        return mycircs

    def test_has_correct_circuits(self):
        stemcircs = self._get_stem_circuits()
        guicircs = self._get_gui_circuits()
        # we want to check for correctness only if were able to
        # detect circuits
        if len(stemcircs) > 0:
            self.assertEqual(stemcircs, guicircs)
        else:
            print("no circuits reported, will skip correctness comparison")

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