# SPDX-FileCopyrightText: 2022 Chris Heywood
#
# SPDX-License-Identifier: GPL-3.0-or-later

import unittest
import warnings

from gi.repository import GLib

from iotas.outline_generator import OutlineGenerator, OutlineHeading
from iotas.note import Note

warnings.filterwarnings("ignore", "version")


class Test(unittest.TestCase):

    headings: list

    def test_generate(self) -> None:
        self.__generate("plain text")
        self.assertEqual(len(self.headings), 0)

        self.__generate("# Heading\n## Second\n### Third\nplain")
        self.assertEqual(len(self.headings), 3)
        heading = self.headings[0]
        self.assertIsInstance(heading, OutlineHeading)
        self.assertEqual(heading.text, "Heading")
        self.assertEqual(heading.line, 0)
        self.assertEqual(heading.level, 1)
        self.assertEqual(heading.indent_level, 0)
        heading = self.headings[1]
        self.assertIsInstance(heading, OutlineHeading)
        self.assertEqual(heading.text, "Second")
        self.assertEqual(heading.line, 1)
        self.assertEqual(heading.level, 2)
        self.assertEqual(heading.indent_level, 1)
        heading = self.headings[2]
        self.assertIsInstance(heading, OutlineHeading)
        self.assertEqual(heading.text, "Third")
        self.assertEqual(heading.line, 2)
        self.assertEqual(heading.level, 3)
        self.assertEqual(heading.indent_level, 2)

        # Test indentation level squashing
        self.__generate("# Heading\n### Second\n#### Third")
        self.assertEqual(len(self.headings), 3)
        heading = self.headings[0]
        self.assertIsInstance(heading, OutlineHeading)
        self.assertEqual(heading.text, "Heading")
        self.assertEqual(heading.line, 0)
        self.assertEqual(heading.level, 1)
        self.assertEqual(heading.indent_level, 0)
        heading = self.headings[1]
        self.assertIsInstance(heading, OutlineHeading)
        self.assertEqual(heading.text, "Second")
        self.assertEqual(heading.line, 1)
        self.assertEqual(heading.level, 3)
        self.assertEqual(heading.indent_level, 1)
        heading = self.headings[2]
        self.assertIsInstance(heading, OutlineHeading)
        self.assertEqual(heading.text, "Third")
        self.assertEqual(heading.line, 2)
        self.assertEqual(heading.level, 4)
        self.assertEqual(heading.indent_level, 2)

    def __generate(self, content: str) -> None:
        generator = OutlineGenerator()
        note = Note(new_note=True)
        note.content = content
        self.done = False
        context = GLib.MainContext.default()
        generator.generate(note, self.__callback)
        while not self.done:
            context.iteration(False)

    def __callback(self, headings: list[OutlineHeading]) -> None:
        self.headings = headings
        self.done = True
