# Functions working with sockets in py2
#
# Copyright (C) 2011 Michal Kajan, Libor Polcak, Petr Kramolis
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import socket
from ..tools.wrapper import Wrapper

class ReconnectingSocket(Wrapper):
    """ A class that reconnects to Unix socket in case of error """

    def __new_socket(self):
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.connect(self.__socket_name)
        return s

    def __init__(self, socket_name):
        """ Constructor """
        self.__socket_name = socket_name
        Wrapper.__init__(self, self.__new_socket())

    def send(self, data):
        """ Extends. Checks for error and reconnects if needed. """
        attempts = 5
        OK = False
        while not OK and attempts > 0:
            try:
                self._wrapped_obj.send(data)
                OK = True
            except socket.error:
                attempts -= 1
                self._wrapped_obj = self.__new_socket()
        if not OK:
            raise socket.error("Cannot send data through socket")

def connectUnixSocket(name):
    """ Connects to unix socket with given name
    
    Performs busy waiting
    """
    OK = False
    while not OK:
        try:
            s = ReconnectingSocket(name)
            OK = True
        except socket.error:
            # Server not ready
            pass
    return s

