"""
RTS Reset Support Implementation

This module provides reset support using RTS (Request To Send) signal
for device reset operations.
"""
from __future__ import annotations

from serial import Serial
from time import sleep
from logging import getLogger

from .reset_support_base import ResetSupportBase
from error.atmosic_error import ResetSupportError
from error.inner_errorcodes import ResetSupportErrorCode

logger = getLogger(__name__)

class RtsResetSupport(ResetSupportBase):
    """Reset support implementation using RTS signal"""
    
    def __init__(self, reset_serial: str = ""):
        """Initialize RTS reset support"""
        logger.info("RtsResetSupport initialized")
        self.serial = reset_serial
        try:
            self.ser = Serial()
            self.ser.port=self.serial
            self.ser.baudrate=115200
            self.ser.timeout=1
            self.ser.rtscts=False
            self.ser.rts = False
            self.ser.open()
        except:
            self.ser = None
            raise ResetSupportError(
                f"Failed to open rts reset support serial port: {self.serial}", 
                ResetSupportErrorCode.PORT_OPEN_FAILED)
    
    def reset_bboot_mode(self, timeout_ms: int = 3000) -> None:
        """Reset device to bboot mode using RTS signal

        Args:
            timeout_ms: Timeout in milliseconds
        """
        assert self.ser is not None
        sleep(0.01)
        self.ser.rts = True
        logger.info("RtsResetSupport: Bboot reset completed")

    def reset_normal_boot(self, timeout_ms: int = 5000) -> None:
        """Reset device to normal boot mode using RTS signal

        Args:
            timeout_ms: Timeout in milliseconds
        """
        logger.error("RtsResetSupport: reset_normal_boot - Not implemented yet")
        raise ResetSupportError("RTS normal boot reset not implemented yet",
                                ResetSupportErrorCode.NOT_IMPLEMENTED)

    def module_stop(self, is_test_success: bool):
        if self.ser is not None:
            self.ser.close()

    def __del__(self):
        logger.info("RtsResetSupport deleted")
        self.module_stop(False)