"""
App to open a channel to a process.
"""

from __future__ import annotations

from moat.lib.micro import AC_use
from moat.lib.rpc.cmd.msg import BaseCmdMsg
from moat.lib.rpc.stream.cmdbbm import BaseCmdBBM
from moat.lib.stream import ProcessBuf, serial_stack


class ProcessCmd(BaseCmdMsg):
    """
    Channel to a process that handles MoaT messages
    """

    argv = None
    path = None

    doc = dict(
        _c=dict(
            _d="Command link to a subprocess",
            command="list[str]:argv",
            path="str:file of executable",
        )
    )

    async def stream(self):  # noqa:D102
        argv = self.cfg["command"] if self.argv is None else self.argv
        path = self.cfg.get("path") if self.path is None else self.path
        if path is None and argv[0][0] == "/":
            path = argv[0]

        proc = ProcessBuf(argv, executable=path)
        return await AC_use(self, serial_stack(proc, cfg=self.cfg))


class ProcessIO(BaseCmdBBM):
    """
    Byte channel to a process that handles arbitrary MaoT messages
    """

    argv = None
    path = None

    doc = dict(
        _c=dict(
            _d="Data link to a subprocess", command="list[str]:argv", path="str:file of executable"
        )
    )

    async def stream(self):  # noqa:D102
        argv = self.cfg["command"] if self.argv is None else self.argv
        path = self.cfg.get("path") if self.path is None else self.path
        if path is None and argv[0][0] == "/":
            path = argv[0]

        proc = ProcessBuf(argv, executable=path)
        return await AC_use(self, proc)
