from debian import substvars
import os
import pathlib
import unittest
import shutil
import sys
import tempfile


def find_pkg_root():
    if not os.environ.get("PKG_KDE_TOOLS_TEST_INSTALLED", False):
        for p in pathlib.Path(__file__).parents:
            if (p/"pkgkde-getqmldepends").exists():
                return p
    return pathlib.Path("/usr/share/pkg-kde-tools")

sys.path.insert(0, str(find_pkg_root()))

from pythonlib import pkgkde

class QmlDependsTestCase(unittest.TestCase):
    def check_substvar(self, fieldname, expected, pkg_name="testpackage"):
        with substvars.Substvars.load_from_path(f"debian/{pkg_name}.substvars") as svars:
            self.assertEqual(svars.get(fieldname, ""), expected)

    def writeControlFile(self):
        with (pathlib.Path(self.tempdir.name)/"debian/control").open("wb") as f:
            self.dc.source.dump(f)
            for pkg in self.dc.packages.values():
                f.write(b"\n")
                pkg.dump(f)

    def setUp(self):
        self.old_cwd = os.getcwd()
        self.tempdir = tempfile.TemporaryDirectory()
        shutil.copytree(pathlib.Path(__file__).with_name("qmltestpackage"), self.tempdir.name, dirs_exist_ok=True)
        os.chdir(self.tempdir.name)
        pathlib.Path("debian/testpackage.substvars").unlink(missing_ok=True)
        self.dc = pkgkde.DebianControl(pathlib.Path("debian/control"))

    def tearDown(self):
        self.tempdir.cleanup()
        os.chdir(self.old_cwd)


