#! /usr/bin/env python3

import socket
import signal
import asyncio
from dataclasses import dataclass

from mqtthandler.command import command
from mqtthandler.handler import MQTTHandler, task

from streamer.fileradio import FileRadio


class RadioHandler(MQTTHandler):
    def __init__(
        self,
        name: str,
    ):
        super().__init__(name)
        self.radio = FileRadio("./data/StarWars60.mp3", name)

    @task
    async def publish_stream_path(self):
        await self.set_property("path", self.radio.stream_path(), qos=1, retain=True)
        await self.set_property("file", self.radio.path, qos=1, retain=True)

    @command({"type": "object"}, "Start the radio stream.")
    async def start(self, args):
        print("Start requested")
        self.radio.start_stream()

    # Manually renamed this one bc it conflicts with the base class version
    @command({"type": "object"}, "Stop the radio stream.", "stop")
    async def stop_stream(self, args):
        print("Stop requested")
        self.radio.end_stream()

    @command({"type": "string"}, "Change the stream path.")
    async def change_path(self, args):
        self.radio = FileRadio(self.radio.path, args)
        await self.publish_stream_path()

    @command({"type": "string"}, "Tune the radio for different playback.")
    async def tune(self, args):
        print("Tune request: ", args)
        self.radio = FileRadio(args, self.radio.name)
        await self.publish_stream_path()


async def main():
    handler = RadioHandler("radio")
    signal.signal(signal.SIGINT, lambda signum, frame: handler.stop())
    await handler.run("127.0.0.1", username="device", password="devicesecret")


if __name__ == "__main__":
    asyncio.run(main())
