import socket
import threading
import ctypes

class RemotePCI(object):
    """Core class for communicating with the remote-pci-register-access server.
    Abstracts socket usage and message parsing away from the user.
    """
    _DEFAULT_PORT = 4444
    _RECV_BUFFER_SIZE = 128
    
    _PROTOCOL_VERSION = 1
    _STATUS_OK = 0
    
    _METHOD_READ = 3
    _METHOD_WRITE = 4
    _METHOD_MODIFY = 5
    
    def __init__(self, host, port=_DEFAULT_PORT, timeout=2, tcp=False):
        self._message_id = 0
        self._host = host
        self._port = port
        self.tcp = tcp
        self._socklock = threading.Lock()
        
        socket_type = socket.SOCK_DGRAM
        if tcp:
            socket_type = socket.SOCK_STREAM
            
        self._socket = socket.socket(socket.AF_INET, socket_type)
        self._socket.settimeout(timeout)
        if tcp:
            self._socket.connect((host, port))

    def __del__(self):
        self._socket.close()

    def read(self, offset, width):
        """Returns data if it was read successfully, else throws an exception."""
        return self._process(offset, width, None, None)
    
    def write(self, offset, width, value):
        """Writes data or throws an exception."""
        self._process(offset, width, value, None)
    
    def modify(self, offset, width, mask_or, mask_and):
        """Modifies the data with OR and AND mask. Returns the change or throws an exception."""
        return self._process(offset, width, mask_or, mask_and)
    
    def _process(self, offset, width, value, value1):
        """Encodes protocol message and sends it to the server.
        Waits for the response, decodes and returns it.
        """
        with self._socklock:
            msg_send = self._encode_msg(offset, width, value, value1)
            msg_recv = self._communicate(msg_send)
            return self._decode_msg(msg_recv)
        
    def _encode_msg(self, offset, width, value, value1):
        """Checks input parameters and throws exception if they are invalid.
        Encodes and returns protocol message.
        """
        if offset < 0:
            raise ValueError("Invalid offset '" + str(offset) + "' specified! Value should be greater or equal to 0!")
        if width != 8 and width != 16 and width != 32:
            raise ValueError("Invalid width '" + str(width) + "' specified! Allowed values: 8/16/32.")
        
        method = RemotePCI._METHOD_READ
        if value is not None:
            method = RemotePCI._METHOD_WRITE
            if value1 is not None:
                method = RemotePCI._METHOD_MODIFY
        
        self._message_id = self._message_id + 1
        msg = str(RemotePCI._PROTOCOL_VERSION) + ","
        msg += str(self._message_id) + ","
        msg += str(offset) + ","
        msg += str(method) + ","
        msg += str(width)
        if value is not None:
            msg += "," + str(value)
            if value1 is not None:
                msg += "," + str(value1)
        msg += ";"
        return msg
    
    def _decode_msg(self, message):
        """Decodes message and returns read data as a signed 32-bit integer.
        If no data was read (in case of write method), returns None.
        Throws ProtocolException in case that decoding fails.
        """
        message = message.split(';')[0]
        data_parts = [s.strip() for s in message.split(',')]
        if len(data_parts) < 3:
            raise RPCIProtocolException("length", len(data_parts), 3)
        
        protocol_version = int(data_parts[0])
        message_id = int(data_parts[1])
        status = int(data_parts[2])
        if protocol_version != RemotePCI._PROTOCOL_VERSION:
            raise RPCIProtocolException("protocol version", protocol_version, RemotePCI._PROTOCOL_VERSION)
        if message_id != self._message_id:
            raise RPCIProtocolException("message id", message_id, self._message_id)
        if status != RemotePCI._STATUS_OK:
            raise RPCIProtocolException("status", status, RemotePCI._STATUS_OK)
        if len(data_parts) > 3:
            val = int(data_parts[3])
            return ctypes.c_long(val).value
        return None
    
    def _communicate(self, data):
        """Sends data over the socket and receives and returns response."""
        if self.tcp:
            self._socket.sendall(data)
            return self._socket.recv(RemotePCI._RECV_BUFFER_SIZE)
        else:
            self._socket.sendto(data, (self._host, self._port))
            recv_data, _ = self._socket.recvfrom(RemotePCI._RECV_BUFFER_SIZE)
            return recv_data
    
    def read_text(self, offset, length):
        """Reads from defined offset specified number of characters/bytes.
        Returns the characters as string.
        """
        text = ""
        for i in range(length):
            b = self.read(offset + i, 8)
            text += chr(b)
        return text

class RPCIProtocolException(Exception):
    """Exception that is thrown when there is a problem with the communication protocol."""
    def __init__(self, var_name, var_value, var_expected):
        self.var_name = var_name
        self.var_value = var_value
        self.var_expected = var_expected
        message = "Value for '" + var_name + "' is '" + str(var_value) + "', but should be '" + str(var_expected) + "'!"
        super(RPCIProtocolException, self).__init__(message)
