#!/usr/bin/env python3

import copy
import os
import subprocess
import sys
import unittest
import shutil

FIXTURES = os.path.join(os.getcwd(), "tests/fixtures")
WORKSPACE = os.path.abspath(os.getenv("WORKSPACE", "/tmp"))
OUT_DIR = os.path.join(WORKSPACE, "out")


def executeAndReturnOutput(command, env={}):
    p = subprocess.Popen(
        command,
        encoding="utf-8",
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env,
    )
    stdoutdata, stderrdata = p.communicate()
    print(stdoutdata, file=sys.stdout)
    print(stderrdata, file=sys.stderr)
    return p.returncode, stdoutdata, stderrdata


command = [
    "./ngcp-memdbg-csv",
]


class TestCommandLine(unittest.TestCase):

    def checkOutFiles(self, dir):
        list_files = os.listdir(OUT_DIR)
        self.assertCountEqual(list_files, os.listdir(dir))
        for _file in list_files:
            res = executeAndReturnOutput(
                [
                    "diff",
                    "-uN",
                    os.path.join(dir, _file),
                    os.path.join(OUT_DIR, _file),
                ],
                None,
            )
            self.assertEqual(res[0], 0, res[1])

    def setUp(self):
        self.command = copy.deepcopy(command)
        if not os.path.exists(OUT_DIR):
            os.makedirs(OUT_DIR)

    def tearDown(self):
        shutil.rmtree(OUT_DIR)

    def testParams(self):
        res = executeAndReturnOutput(self.command)
        self.assertNotEqual(res[0], 0)
        self.assertRegex(res[2], "wrong number of parameters")

    def testParams_nofile(self):
        self.command.append("fake_file")
        self.command.append(OUT_DIR)
        res = executeAndReturnOutput(self.command)
        self.assertNotEqual(res[0], 0)
        self.assertRegex(res[2], "Couldn't open kamailio log")

    def testParams_nodir(self):
        self.command.append(os.path.join(FIXTURES, "kam1.log"))
        self.command.append("fake_dir")
        res = executeAndReturnOutput(self.command)
        self.assertNotEqual(res[0], 0)
        self.assertRegex(res[2], "fake_dir doesn't exists")

    def _test_kam(self, name):
        self.command.append(os.path.join(FIXTURES, "%s.log" % name))
        self.command.append(OUT_DIR)
        res = executeAndReturnOutput(self.command)
        self.assertEqual(res[0], 0)
        self.checkOutFiles(os.path.join(FIXTURES, name))

    def test_kam0(self):
        self._test_kam("kam0")

    def test_kam1(self):
        self._test_kam("kam1")

    def test_kam2(self):
        self._test_kam("kam2")

    def test_kam3(self):
        self._test_kam("kam3")

    def test_kam4(self):
        self._test_kam("kam4")
