#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
stringtools.csp (Carriage-Return seperation protocol)
=====================================================

**Author:**

* Dirk Alders <sudo-dirk@mount-mockery.de>

**Description:**

    This module is a submodule of :mod:`stringtools` and creates an frame to transmit and receive messages via an serial interface.

**Submodules:**

* :class:`stringtools.csp.csp`
* :func:`stringtools.csp.build_frame`
"""

import stringtools

import logging
import sys

try:
    from config import APP_NAME as ROOT_LOGGER_NAME
except ImportError:
    ROOT_LOGGER_NAME = 'root'
logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)

DATA_SEPERATOR = b'\n'


class csp(object):
    """This class extracts messages from an "csp-stream".

    **Example:**

    .. literalinclude:: stringtools/_examples_/csp.csp.py

    Will result to the following output:

    .. literalinclude:: stringtools/_examples_/csp.csp.log
    """
    LOG_PREFIX = 'CSP:'

    def __init__(self, seperator=DATA_SEPERATOR):
        self.__buffer__ = b''
        self.__seperator__ = seperator

    def process(self, data):
        """
        This processes a byte out of a "stp-stream".

        :param bytes data: A byte stream
        :returns: A list of the extracted message(s)
        :rtype: list
        """
        rv = (self.__buffer__ + data).split(self.__seperator__)
        self.__buffer__ = rv.pop()
        if len(self.__buffer__) != 0:
            logger.debug('%s Leaving data in buffer (to be processed next time): %s', self.LOG_PREFIX, stringtools.hexlify(self.__buffer__))
        for msg in rv:
            logger.info('%s message identified - %s', self.LOG_PREFIX, stringtools.hexlify(msg))
        return rv


def build_frame(msg, seperator=DATA_SEPERATOR):
    """This Method builds an "csp-frame" to be transfered via a stream.

    :param str data: A String (Bytes) to be framed
    :returns: The "csp-framed" message to be sent
    :rtype: str

    **Example:**

    .. literalinclude:: stringtools/_examples_/csp.build_frame.py

    Will result to the following output:

    .. literalinclude:: stringtools/_examples_/csp.build_frame.log
    """
    if seperator in msg:
        raise ValueError
    else:
        return msg + seperator
