# Echo server program
import socket
import sys
import os
import time


def Server():
    """
    Ethernet Server (GNSS prototyp)
    Read nmea example and will send it to server
    """
    # ---------------------------------------read file----------------------------------------------------------------------
    path = os.path.normpath("\\nmea_example_1.txt")
    path = os.path.normpath(os.getcwd()) + path
    infile = open(path, 'r')
    lines_infile = infile.readlines()
    infile.close()
    # ---------------------------------------ethernet setup-----------------------------------------------------------------
    HOST = None  # Symbolic name meaning all available interfaces
    PORT = 50007  # Arbitrary non-privileged port
    s = None
    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error as msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
            print 'Wait for host...'
        except socket.error as msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
        sys.exit(1)
    conn, addr = s.accept()
    print 'Connected by', addr
    send(lines_infile, conn)
    conn.close()


# ---------------------------------------port write---------------------------------------------------------------------
def send(lines, conn):
    a = 1
    i = 0
    for line in lines:
        if line == "\n":
            continue
        if i == 100:
            print("Odeslano celkove: %i00 NMEA vet" % a)
            a += 1
            i = 0
        i += 1
        conn.send(line.rstrip())
        data = conn.recv(1024)
        if data == 'quit':
            break
        if data:
            print 'Received:', repr(data)
        time.sleep(0.1)


if __name__ == '__main__':
    Server()
