# -*- coding: utf-8 -*-
'''
    This module implements unit tests of the actev get-system command.
'''

import sys
import os
import shutil
import unittest
import argparse

from diva_evaluation_cli.bin.cli import cli_parser


def _clean_tmp_folder():
    try:
        shutil.rmtree('tmp')
    except Exception as e:
        pass
    finally:
        os.mkdir('tmp')


class TestGetSystemGit(unittest.TestCase):
    """
    Test the actev get-system git --sha CLI call, using valid and invalid
    parameters
    """

    def setUp(self):
        self.gitURL = "https://gitlab.kitware.com/actev/diva_evaluation_cli" \
                      ".git"
        _clean_tmp_folder()

    def test_git_subcommand(self):
        def _update_argv(args: list):
            # Use this to modify CLI parameters
            if isinstance(args, str):
                args = [args]
            sys.argv[1:] = ['get-system', 'git'] + args
        ##################
        # Checking --sha #
        ##################
        args = ['-u',
                self.gitURL,
                '-l',
                'tmp',
                '--sha']

        # 0. No parameter
        _update_argv(args)
        with self.assertRaises(SystemExit):
            cli_parser()
            self.fail('System does not stop on invalid input.')
        _clean_tmp_folder()

        # 1. Correct tag
        _update_argv(args + ['tags/1.0'])
        try:
            cli_parser()
        except Exception:
            self.fail('Could not checkout on tag `development`')
        _clean_tmp_folder()

        # 2. Incorrect tag
        _update_argv(args + ['tags/0.1'])
        with self.assertRaises(SystemExit):
            cli_parser()
            self.fail('The system managed to checkout on invalid tag `0.1`')

        # 3. Correct SHA
        _update_argv(args + ['eb26f205'])
        try:
            cli_parser()
        except Exception:
            self.fail('Could not checkout on commit `eb26f205`')
        _clean_tmp_folder()

        # 4. Incorrect SHA
        _update_argv(args + ['abcdefgh'])
        with self.assertRaises(SystemExit):
            cli_parser()
            self.fail(
                'The system managed to checkout on invalid commit `abcdefgh`')
        _clean_tmp_folder()

    def tearDown(self):
        # Clear archive and repository
        shutil.rmtree('tmp')


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