#!/usr/bin/env python
# encoding: utf-8
"""This is a script to test and use the ns3 RaLaNS application"""
########################################################################################################################
# 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 numpy as np
import matplotlib.pyplot as plt
import math
from optparse import OptionParser

INTERPOLATE = True
BORDERS = [-52, -28, 55, 22]
STEPWIDTH = 0.5
TRANSMITTER = [0, 0, 1]
THRESHOLD = 0.0
MAPFILE = "/home/USER/PATH-TO-DEFAULT-ZIP-OR-TXT-FILE"
BADNUM = 0
LISTINTERPOLATIONNUM = 2
NOSIGNAL = -3076.53

parser = OptionParser()
parser.add_option("-t", "--transmitter", dest="transmitter", default=TRANSMITTER,
        help="set transmitter to check signals strengths for, has to be a 3d point and in [] braces,\
                float numbers allowed, f.x. [0,0,1]", 
                metavar="STRING")
parser.add_option("-b", "--borders",
        dest="borders", default=BORDERS,
        help="set Borders for quering signal strengths in, [beginXAxis,beginYAXIS,endXAxis,endYAxis],\
                f.x. [-100,-100,100,100] ", metavar="STRING")
parser.add_option("-s", "--stepwidth",
        dest="stepwidth", default=STEPWIDTH,
        help="set stepwidth, can not be 0, float numbers allowd, only positive values allowed, f.x. 1", 
        metavar="DOUBLE")
parser.add_option("-i", "--nointerpolate",
        action="store_false", dest="interpolate",
        help="set the option to not interpolate between the signal strengths")
parser.add_option("-d", "--threshold",
        dest="threshold", default=THRESHOLD,
        help="set threshold, a float value >= 0, f.x. 0.5", 
        metavar="DOUBLE")
parser.add_option("-m", "--mapfile",
        dest="mapfile", default=MAPFILE,
        help="set mapfile, the path to file, which contains the data, path can be absolute or relative",
        metavar="STRING")
parser.add_option("--bn", "--badnum",
        dest="badnum", default=BADNUM,
        help="set badnum, a value, to exlude max. badnum times a nosignal value",
        metavar="INTEGER")
parser.add_option("-l", "--listinterpolationnum",
        dest="listinterpolationnum", default=LISTINTERPOLATIONNUM,
        help="set listinterpolationnum, this value decides how many points are interpolated around a query point, if\
                the calculation is done with lists",
                metavar="INTEGER")
parser.add_option("-n", "--nosignal",
        dest="nosignal", default=NOSIGNAL,
        help="set nosignal, every signal value, which is below this value, will be setted to this value",
        metavar="DOUBLE")
parser.add_option("-p", "--saveFolderPicture",
        dest="savefolder", default="",
        help="specify the folder for saving the generated figure. If this parameter is set there will be a saved file\
        with the name of the given data file and the setted parameters.",
        metavar="STRING")

(options, args) = parser.parse_args()

transmitterstring = "".join(str(options.transmitter).split())  #remove whitespaces
borderstring = "".join(str(options.borders).split())
stepwidthstring = str(options.stepwidth)
thresholdstring = str(options.threshold)
mapfilestring = str(options.mapfile)
badnumstring = str(options.badnum)
listinterpolationnumstring = str(options.listinterpolationnum)
nosignalstring = str(options.nosignal)
savefolderstring = str(options.savefolder)


command = './waf --pyrun "scratch/ralans_example.py --transmitter=' + transmitterstring + ' --borders='\
        + borderstring + ' --threshold='+ thresholdstring + ' --mapFile=' + mapfilestring +\
        ' --stepwidth=' + stepwidthstring + ' --badnum=' + badnumstring +\
        ' --listinterpolationnum=' + listinterpolationnumstring + ' --nosignal=' + nosignalstring
if options.interpolate == False:
    command += ' --interpolate '
command += '" 2>powerlog'
os.system(command)

borders = eval(borderstring)
transmitter = eval(transmitterstring)
stepwidth = float(stepwidthstring)
#The powerlog file now contains the receiver power for all sent packets.
values = []
for l in open("powerlog", "r"):
    try:
        val = l.split("rxPower=")[-1].split("dbm")[0]
        values.append(float(val))
    except:
        #print all other lines, they may contain valuable debugging information
        print l

#Plot the rxPower values:
xlen = math.ceil((borders[2] - borders[0]) / stepwidth)
ylen = math.ceil((borders[3] - borders[1]) / stepwidth)
values = np.reshape(values, (xlen, ylen))


values = np.transpose(values)
plt.imshow(values, vmin=-100, vmax=0, interpolation="nearest", cmap=plt.get_cmap("gnuplot2"),
        origin="lower", extent=np.array(borders)[[0, 2, 1, 3]])
cb = plt.colorbar()
plt.ylabel("y [m]")
plt.xlabel("x [m]")
cb.set_label("received power [dBm]")

if options.savefolder != "":
    #Save the plot to a svg file

    #get last element from filePath, which is the name
    pathToFileList = mapfilestring.split("/")
    fileName = pathToFileList[-1]

    #remove .txt or .zip from fileName
    fileName = fileName[:-4]

    interpolate = "YES"
    if options.interpolate == False:
        interpolate = "NO"
    savename = savefolderstring + fileName + "_TRANS=" + transmitterstring + "_THRES=" + thresholdstring + "_STEPS=" +\
    stepwidthstring + "_INTER=" + interpolate + "_NOSIGNAL=" + nosignalstring + "_BADNUM=" + badnumstring +\
    "_LISTINTERPOLNUM=" + listinterpolationnumstring + ".svg"
    plt.savefig(savename)

#show the plot
plt.show()
