#!/usr/bin/env python3
import copy
import os
import subprocess
import sys
import unittest

FIXTURES = os.path.join(os.getcwd(), "tests/fixtures")
CFG_CE = os.path.join(FIXTURES, "cfg_schema_ce.db")


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-check-rev-applied", "--debug", "--schema", "cfg_schema"]


class TestCommandLine(unittest.TestCase):
    def setUp(self):
        self.command = copy.deepcopy(command)

    def testWrongParam(self):
        self.command.append("--fake-param")
        res = executeAndReturnOutput(self.command)
        self.assertNotEqual(res[0], 0)
        self.assertRegex(res[2], "Unknown option: fake-param")


class TestCfgCE(unittest.TestCase):
    def setUp(self):
        self.command = copy.deepcopy(command)
        self.command.append("--dbfile")
        self.command.append(CFG_CE)

    def _testOk(self, name):
        self.command.append("--revision")
        self.command.append(name)
        res = executeAndReturnOutput(self.command)
        self.assertEqual(res[0], 0)
        self.assertRegex(res[1], "Revision {} already executed".format(name))

    def testNonAppliedRev(self):
        self.command.append("--revision")
        self.command.append("whatever")
        res = executeAndReturnOutput(self.command)
        self.assertNotEqual(res[0], 0)
        self.assertRegex(res[1], "No match for revision whatever")

    def testRev(self):
        self._testOk("901000078")

    def testRevZeros(self):
        self._testOk("00000901000078")

    def testRevName(self):
        self._testOk("901000078_kamailio_proxy_lcr_stopper_mode.up")

    def testRevFullPath(self):
        name = (
            "/usr/share/ngcp-cfg-schema/cfg_scripts/config/"
            "901000078_kamailio_proxy_lcr_stopper_mode.up"
        )
        self._testOk(name)

    def testRevWrongNode(self):
        self.command.append("--node")
        self.command.append("sp1")
        self.command.append("--revision")
        self.command.append("901000078")
        res = executeAndReturnOutput(self.command)
        self.assertNotEqual(res[0], 0)
        self.assertRegex(res[1], "No match for revision 901000078 on host sp1")

    def testRevMulti(self):
        self.command.append("--revision")
        self.command.append("901000078")
        self.command.append("901000092")
        self.command.append("901000102")
        res = executeAndReturnOutput(self.command)
        self.assertEqual(res[0], 0)
        self.assertRegex(res[1], "Revision 901000078 already executed")
        self.assertRegex(res[1], "Revision 901000092 already executed")
        self.assertRegex(res[1], "Revision 901000102 already executed")
