import unittest
from modelverse_kernel.main import ModelverseKernel
from utils import execute_until_finished, MvSWrapper, get_inst, get_phase, get_returnvalue

class TestDeclare(unittest.TestCase):
    def setUp(self):
        self.mvs = MvSWrapper()
        self.root = self.mvs.execute("RR", [])[0]
        self.mvk = ModelverseKernel(self.root)

        self.task_root = self.mvs.execute("CN", [])[0]
        self.globals = self.mvs.execute("CN", [])[0]
        self.task_frame = self.mvs.execute("CN", [])[0]
        self.symbols = self.mvs.execute("CN", [])[0]
        self.evalstack = self.mvs.execute("CN", [])[0]
        self.returnvalue = self.mvs.execute("CN", [])[0]
        self.phase = self.mvs.execute("CNV", ["init"])[0]

        self.mvs.execute("CD", [self.root, "task_1", self.task_root])
        self.mvs.execute("CD", [self.task_root, "frame", self.task_frame])
        self.mvs.execute("CD", [self.task_root, "globals", self.globals])
        self.mvs.execute("CD", [self.task_frame, "symbols", self.symbols])
        self.mvs.execute("CD", [self.task_frame, "evalstack", self.evalstack])
        self.mvs.execute("CD", [self.task_frame, "phase", self.phase])
        self.mvs.execute("CD", [self.task_frame, "returnvalue", self.returnvalue])

    def test_declare(self):
        self.inst = self.mvs.execute("CNV", [{"value":"declare"}])[0]
        self.var = self.mvs.execute("CN", [])[0]

        self.mvs.execute("CD", [self.task_frame, "IP", self.inst])
        self.mvs.execute("CD", [self.inst, "var", self.var])

        ### Execute rules
        self.assertEquals(get_inst(self.root, self.mvs), "declare")
        self.assertEquals(get_phase(self.root, self.mvs), "init")
        execute_until_finished(self.mvk, self.mvs)

        self.assertEquals(get_inst(self.root, self.mvs), "declare")
        self.assertEquals(get_phase(self.root, self.mvs), "finish")
        self.assertNotEquals(self.mvs.execute("RDN", [self.symbols, self.var])[0], None)

    def test_global(self):
        self.global_symbols = self.mvs.execute("RD", [self.task_root, "globals"])[0]
        self.inst = self.mvs.execute("CNV", [{"value":"global"}])[0]
        self.var = self.mvs.execute("CNV", ["abc"])[0]

        self.mvs.execute("CD", [self.task_frame, "IP", self.inst])
        self.mvs.execute("CD", [self.inst, "var", self.var])

        ### Execute rules
        self.assertEquals(get_inst(self.root, self.mvs), "global")
        self.assertEquals(get_phase(self.root, self.mvs), "init")
        execute_until_finished(self.mvk, self.mvs)

        self.assertEquals(get_inst(self.root, self.mvs), "global")
        self.assertEquals(get_phase(self.root, self.mvs), "finish")
        self.assertNotEquals(self.mvs.execute("RD", [self.global_symbols, "abc"])[0], None)
