from __future__ import print_function
import math
import os
import shutil
import struct
import tempfile
import unittest
import wave
from bayouradar_skywarn.audio import AudioRenderer


class AudioRendererTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.mkdtemp(prefix="brs-audio-test-")

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

    def _tone(self, path, seconds=0.08):
        rate = 8000
        with wave.open(path, "wb") as handle:
            handle.setnchannels(1)
            handle.setsampwidth(2)
            handle.setframerate(rate)
            frames = []
            for index in range(int(rate * seconds)):
                sample = int(7000 * math.sin(2 * math.pi * 440 * index / rate))
                frames.append(struct.pack("<h", sample))
            handle.writeframes(b"".join(frames))

    def test_prefix_delay_and_speech_create_ulaw(self):
        if not shutil.which("ffmpeg") or not (shutil.which("espeak-ng") or shutil.which("espeak")):
            self.skipTest("ffmpeg and espeak are required")
        prefix = os.path.join(self.tmp, "prefix.wav")
        self._tone(prefix)
        renderer = AudioRenderer({
            "enabled": True,
            "engine": "espeak",
            "voice": "en-us",
            "rate": 155,
            "ffmpeg_binary": shutil.which("ffmpeg"),
            "delay_ms": 80,
            "keep_generated": False,
        }, self.tmp)
        base = renderer.render("Bayou Radar Skywarn audio test.", "composed", [prefix], [])
        target = base + ".ulaw"
        self.assertTrue(os.path.exists(target))
        self.assertGreater(os.path.getsize(target), 1000)
        with open(target, "rb") as handle:
            self.assertTrue(handle.read(32))


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