
########################################################################################################################
# Copyright (c) 2015, University of Osnabrueck                                                                         #
#   All rights reserved.                                                                                               #
#                                                                                                                      #
#   Redistribution and use in source and binary forms, with or without modification, are permitted provided that the   #
#   following conditions are met:                                                                                      #
#                                                                                                                      #
#   1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following#
#       disclaimer.                                                                                                    #
#                                                                                                                      #
#   2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       #
#       following disclaimer in the documentation and/or other materials provided with the distribution.               #
#                                                                                                                      #
#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, #
#   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE  #
#   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR    #
#   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,  #
#   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE   #
#   USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                                           #
########################################################################################################################
import os
import sys

sys.path.append('src/util')
import shutil
import networking
import marshal
from src.launcher import wrapLauncher
import build_native
import socket
import src.globals as gl
import logging

def main():
    build_native.build()

    identifier = "network" + socket.gethostname()

    fTmp = "tmp/"
    gl.rmdir(fTmp)
    gl.mkdir(fTmp)
    workfolder = fTmp + identifier + "/"
    fLogs = workfolder + "logs/"

    gl.mkdir(fTmp)
    gl.mkdir(workfolder)
    gl.mkdir(fLogs)

    gl.initLogger(fLogs, identifier)
    coveragefolder = workfolder + "coverage/"
    gl.mkdir(coveragefolder)
    rayfolder = workfolder + "rays/"
    gl.mkdir(rayfolder)

    buildingspolyfilename = workfolder + identifier + "_buildingspoly.txt"
    terrainpolyfilename = workfolder + identifier + "_terrainpoly.txt"
    buildingsedgesfilename = workfolder + identifier + "_buildingsedges.txt"
    terrainedgesfilename = workfolder + identifier + "_terrainedges.txt"
    receiverfile = workfolder + "receiverlist.cfg"


    # receive all required data:
    gl.logger.info("Receiving required data...")
    sock, conn = networking.startLinkServer()
    for filename in [buildingspolyfilename, terrainpolyfilename]:
        data = networking.receive(conn)
        f = open(filename, "wb")
        f.write(data)
        f.close()
    transmitters = marshal.loads(networking.receive(conn))
    config = marshal.loads(networking.receive(conn))
    if config["receiverType"] == 4:
        data = networking.receive(conn)
        f = open(receiverfile, "wb")
        f.write(data)
        f.close()

    conn.close()
    sock.close()
    gl.logger.info("\t... data received.")
    if(config["debugLevel"] == 5):
        gl.logger.setLevel(logging.DEBUG)


    #do simulation:
    wrapLauncher.calculateTransmitterParallel(coveragefolder, buildingspolyfilename, terrainpolyfilename,
                                              buildingsedgesfilename, terrainedgesfilename, rayfolder, transmitters,
                                              config, receiverfile)

    print "Sending calculated data..."
    #send generated data:
    sock, conn = networking.startLinkServer()
    networking.send(identifier, conn)
    for transmitter in transmitters:
        x,y,z = transmitter
        transmitter = "[{:g}, {:g}, {:g}]".format(x,y,z)
        f = open(coveragefolder + str(transmitter) + '.txt', 'r')
        data = f.read()
        networking.send(data, conn)
        f.close()
        if config["debugRays"] is True:
            f = open(rayfolder + str(transmitter) + '.txt', 'r')
            data = f.read()
            networking.send(data, conn)
            f.close()
    f = open(fLogs + identifier + ".log", 'r')
    data = f.read()
    f.close()
    networking.send(data, conn)
    f = open(fLogs + identifier + "_launcher.log", 'r')
    data = f.read()
    f.close()
    networking.send(data, conn)
    conn.close()
    sock.close()
    print "Finished"



if __name__ == "__main__":
    main()





