#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2016 Simon McVittie <smcv@debian.org>
# SPDX-License-Identifier: GPL-2.0-or-later

import os
import subprocess
import sys
import unittest
from tempfile import (TemporaryDirectory)

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))


class DownloadSharewareTestCase(unittest.TestCase):
    '''
    Test some cherry picked games that:
    - are freely downloadable (either demo or full version)
    - test various codepaths:
      - alternatives
      - archive recursion (zip in zip)
      - lha
      - id-shr-extract
    - doom_common.py plugin
    - are not too big
    '''

    def setUp(self) -> None:
        if 'GDP_MIRROR' in os.environ:
            self.downloads = None
            if os.environ['GDP_MIRROR'] == 'none':
                self.skipTest('GDP_MIRROR is set to "none"')
        else:
            try:
                from gi.repository import GLib
            except ImportError:
                self.skipTest('GLib g-i bindings not available')

            self.downloads = GLib.get_user_special_dir(
                    GLib.UserDirectory.DIRECTORY_DOWNLOAD)
            if (self.downloads is None or
                    not os.path.isdir(self.downloads)):
                self.skipTest('XDG download directory "{}" not found'.format(
                    self.downloads))

            os.environ['GDP_MIRROR'] = 'file://' + self.downloads

    def _test_one(self, game: str, files: list[str]) -> None:
        if self.downloads is not None:
            for filename in files:
                if not os.path.exists(os.path.join(self.downloads, filename)):
                    self.skipTest('download {} into {}'.format(filename,
                                  self.downloads))

        with TemporaryDirectory(prefix='gdptest.') as tmp:
            if 'GDP_UNINSTALLED' in os.environ:
                argv = [
                    os.path.join(
                        os.environ.get('GDP_BUILDDIR', 'out'),
                        'run-gdp-uninstalled',
                    )
                ]
            else:
                argv = ['game-data-packager']

            argv = argv + [
                '-d', tmp,
                '--no-compress',
                game,
                '--no-search',
            ]
            subprocess.check_call(argv)
            if 'GDP_TEST_ALL_FORMATS' in os.environ:
                for f in 'arch deb rpm'.split():
                    subprocess.check_call(argv + ['--target-format', f])

    def test_heretic(self) -> None:
        self._test_one('heretic', 'htic_v12.zip'.split())

    def test_rott(self) -> None:
        self._test_one('rott', '1rott13.zip'.split())

    def test_spear(self) -> None:
        self._test_one('spear-of-destiny', 'sodemo.zip destiny.zip'.split())

    def test_wolf3d(self) -> None:
        self._test_one('wolf3d', '1wolf14.zip'.split())

    def tearDown(self) -> None:
        pass


if __name__ == '__main__':
    if 'DEB_BUILD_TIME_TESTS' in os.environ:
        print('# SKIP: not doing test that requires network access at '
              'build-time')
    else:
        from gdp_test_common import main
        main()
