import importlib.util
import sys
import unittest
from pathlib import Path


def load_package():
    package_dir = Path(__file__).resolve().parents[1] / "kocoafab-robodog"
    init_py = package_dir / "__init__.py"
    spec = importlib.util.spec_from_file_location(
        "kocoafab_robodog",
        init_py,
        submodule_search_locations=[str(package_dir)],
    )
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module


class SoundApiTest(unittest.TestCase):
    def test_sound_constants_encode_theme_in_track_value(self):
        package = load_package()

        self.assertEqual(1, package.멍멍)
        self.assertEqual(11, package.안녕)
        self.assertEqual(21, package.레이저)
        self.assertEqual(31, package.도)

    def test_sound_accepts_track_and_volume(self):
        package = load_package()
        dog = package.RoboDog()

        dog.sound(package.안녕, package.크게)
        first_packet = dog.makepkt.getCopiedPacket()

        self.assertEqual(11, first_packet[7] & 0x7F)
        self.assertEqual(package.크게, first_packet[8])
        self.assertEqual(0x80, first_packet[7] & 0x80)

        dog.sound(package.안녕, package.크게)
        second_packet = dog.makepkt.getCopiedPacket()

        self.assertEqual(11, second_packet[7] & 0x7F)
        self.assertEqual(0, second_packet[7] & 0x80)

    def test_sound_keeps_legacy_signature_compatible_with_encoded_tracks(self):
        package = load_package()
        dog = package.RoboDog()

        dog.sound(package.명령어, package.안녕, package.중간)
        packet = dog.makepkt.getCopiedPacket()

        self.assertEqual(11, packet[7] & 0x7F)
        self.assertEqual(package.중간, packet[8])

    def test_multi_sound_accepts_track_and_volume(self):
        package = load_package()
        dogs = [package.RoboDog(), package.RoboDog()]

        package.multi_sound(dogs, package.레이저, package.작게)

        for dog in dogs:
            packet = dog.makepkt.getCopiedPacket()
            self.assertEqual(21, packet[7] & 0x7F)
            self.assertEqual(package.작게, packet[8])


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