import can
from typing import Literal

from pydantic import Field
from .generic_node import GenericCanNode


class KvaeserCanNode(GenericCanNode):
    class Config(GenericCanNode.Config):
        type: Literal["kvaeser_can"]
        channel: int = Field(default=0, title="Channel to connect to")

        @classmethod
        def default(cls):
            return cls(type="kvaeser_can", channel=cls.channel)

    config: Config

    def __init__(self, config: Config):
        super().__init__(config)

    def init(self):
        super().init()

        self.bus = can.interface.Bus(
            bustype="kvaser",
            channel=self.config.channel,
            bitrate=self.config.bitrate if isinstance(self.config.bitrate, int) else self.config.bitrate.value,
        )
