"""Implemets the TCP client logic"""

import socket, core_to_xml, globalv, time
from cache import FIFOBuffer

__warteListe = FIFOBuffer()
to_xml = core_to_xml.CreateXml()

def send(type, args_dict, tries = 1):
    """sends a murray-packet via TCP Socket. Takes a dictionary and the 
    number of attempted sends as arguments
    
    DO NOT USE 'tries' I MEAN IT!"""
    if args_dict['destination']['ipversion'] == 6:
        raise NotImplementedError
    else:
        ip = args_dict['destination']['ip']
        port = int(args_dict['destination']['port'])
        xml = to_xml.incoming(type, args_dict)
        try:
            sendIPv4((ip, port), xml)
        except socket.error:
            __warteListe.add(((tries + 1), args_dict))

def sendIPv4(host, message):
    """send over IPv4 Network"""
    sock = socket.socket()
    sock.connect(host)
    snake = len(message)
    plane = sock.send(message)
    while plane < snake:
        message = message[plane:]
        snake = len(message)
        plane = sock.send(message)
    sock.close()
    
    
def resend(maxtries = 3):
    """resend failed messages"""
    while globalv.RUNNING:
        time.sleep(10)
        item = __warteListe.get()
        if item and item[0] <= maxtries:
            send(item[1], tries = item[0])
        else: pass
