#####
# wsr - worksite sense range
#

import crData;
import pyCreeper;
pyCreeper.crGraphs.DEBUG_LEVEL = 0;

import analysis;

import constants;
import numpy;
import visualisation;

experimentNamePrefix = "static_wsr2500"
envs = ['heap1-7000','heap3-7000','scatter12-7000','heap1-14000','heap3-14000','scatter12-14000']; #'heap1-7000'
#envs = ['heap3-7000','scatter12-7000','heap3-14000','scatter12-14000']; #'heap1-7000'
#envs = ['heap1-7000','heap3-7000','heap1-14000','heap3-14000','scatter12-14000'];

nrVals = [5];
#controllers = ['S','S'];
#legendLabels = ['solitary','local broadcaster'];
controllers = ['S','LB_commD12500','S_OLDmov']; #LB_commD12500
legendLabels = ['solitary','local broadcaster','S_OLDmov'];

controllers = ['S'];
legendLabels = ['solitary'];

controllers = ['S','S_OLDmov'];
legendLabels = ['solitary','S_OLDmov'];

controllers = ['S','LB_commD12500'];
legendLabels = ['solitary','local broadcaster'];
numRuns = 10;

CHECK_NUM_ROBOT_FAILURES = False;
CHECK_NUM_RUNS_WITH_FAILUERS = True;
CHECK_TOTAL_ROBOT_FAILURE_TIME = True;
CHECK_RESOURCE_LOST = False;
CHECK_RECRUITMENT_VS_SCOUTING = False;

for nr in range(len(nrVals)):
    nrVal = nrVals[nr];

    results_numOfRobotFailures = [[[0 for i in range(numRuns)] for j in range(len(envs))] for c in range(len(controllers))];
    results_timeOfRobotFailures = [[[0 for i in range(numRuns)] for j in range(len(envs))] for c in range(len(controllers))];
    results_resourceLost = [[[0 for i in range(numRuns)] for j in range(len(envs))] for c in range(len(controllers))];
    results_numRunsWithRobotFailuers = [[0 for j in range(len(envs))] for c in range(len(controllers))];
    results_recruitmentVsScouting = [[[0 for i in range(numRuns)] for j in range(len(envs))] for c in range(len(controllers))];


    for c in range(len(controllers)):
        controllerVal = controllers[c];
        print(controllerVal);

        for env in range(len(envs)):
            envName = envs[env];
            print(envName)

            if ("gpev2000" in experimentNamePrefix and "heap1" in envName):
                results_numOfRobotFailures[c][env][0] = 999;
                results_timeOfRobotFailures[c][env][0] = 10;
                results_resourceLost[c][env][0] = 999;
                results_numRunsWithRobotFailuers[c][env] = 999;
                continue;

            for runNo in range(numRuns):

                runDataPathPrefix = "{}/NR{}_FOR_{}_{}/run{}".format(experimentNamePrefix, nrVal, envName, controllerVal, runNo);

                runData = crData.fileToArray((constants.DATA_PATH + "/{}_infoEvents.txt").format(runDataPathPrefix), "\t", True);
                latestRewardReceivedEventTime = -1;

                runCompletionTime = analysis.getRunCompletionTime(runDataPathPrefix,False);

                resourceCollected = 0;

                # -- go through each row of run data
                hasFailure = False;
                numScoutingEvents = 0;
                numRecruitmentEvents = 0;
                for i in range(len(runData)):
                    eventType = runData[i][1];
                    time = runData[i][0];

                    if (CHECK_NUM_ROBOT_FAILURES):
                        if (eventType == constants.E_ROBOT_BROKE):
                            results_numOfRobotFailures[c][env][runNo] += 1;

                    if (CHECK_NUM_RUNS_WITH_FAILUERS):
                        if (eventType == constants.E_ROBOT_BROKE):
                            hasFailure = True;

                    if (CHECK_TOTAL_ROBOT_FAILURE_TIME):
                        if (eventType == constants.E_ROBOT_BROKE):

                            #-- always, the robot fixed will be the following line
                            fixedTime = runData[i+1][0];
                            print("run{} failure started at t={} finished at t={}".format(runNo,time, fixedTime));
                            if (fixedTime > runCompletionTime):
                                fixedTime = runCompletionTime;
                                print (" ! adjusted to run completion time={}".format(runCompletionTime));

                            failureTime = fixedTime - time;
                            failureTimeAdj = failureTime / (1.0*runCompletionTime*nrVal);
                            print(" > failure time={} adjusted for completion time {} = {}".format(failureTime,runCompletionTime,failureTimeAdj));

                            results_timeOfRobotFailures[c][env][runNo] += failureTimeAdj; # as percentage from total completion time, per robot



                    if (CHECK_RECRUITMENT_VS_SCOUTING):
                        if (eventType == constants.E_ROBOT_RECRUITED):
                            numRecruitmentEvents += 1;
                        elif (eventType == constants.E_SITE_SCOUTED):
                            numScoutingEvents += 1;





                if (CHECK_RECRUITMENT_VS_SCOUTING):
                    results_recruitmentVsScouting[c][env][runNo] = numRecruitmentEvents / (numScoutingEvents * 1.0)
                    print(" Run {} recruitment {} scouting {} vs {}".format(runNo, numRecruitmentEvents, numScoutingEvents, results_recruitmentVsScouting[c][env][runNo]));

                if (hasFailure):
                    #results_numRunsWithRobotFailuers[c][env] += (1.0 / numRuns) * 100;
                    results_numRunsWithRobotFailuers[c][env] += 1

    print("======")
    markers, lineStyles = visualisation.getPlotStylesForControllers(controllers,[experimentNamePrefix for x in range(len(controllers))]);

    print(markers);
    if (CHECK_NUM_ROBOT_FAILURES):
        #print(results_numOfRobotFailures);
        pyCreeper.crGraphs.createLinePlot(results_numOfRobotFailures,yLabel_="Number of robot failures", xTickLabels_=envs, showAverages_=True, legendLabels_=legendLabels, filePath_="", size_=(20,5), gridType_=pyCreeper.crGraphs.GRID_TYPE.MAJOR, markerSize_=5, lineWidth_=0);

    if (CHECK_NUM_RUNS_WITH_FAILUERS):
        #print(results_numRunsWithRobotFailuers);
        plotFilePath = "{}/{}/numRunsWithFailures_NR{}.png".format(constants.PLOTS_PATH, experimentNamePrefix, nrVal);
        plotFilePath = ""
        pyCreeper.crGraphs.createLinePlot(results_numRunsWithRobotFailuers,yLabel_="% of runs with robot failures", markers_=markers, xTickLabels_=envs,legendLabels_=legendLabels, yMin_=0,yMax_=10, yTicksStep_=1, showAverages_=True, filePath_=plotFilePath, size_=(20,5), gridType_=pyCreeper.crGraphs.GRID_TYPE.MAJOR, markerSize_=15, lineWidth_=0);


    if (CHECK_TOTAL_ROBOT_FAILURE_TIME):
        #print(results_timeOfRobotFailures);
        for c in range(len(controllers)):
            for env in range(len(envs)):
                for runNo in range(numRuns):
                    #results_timeOfRobotFailures[env][runNo] /= 60.0; #convert to minutes
                    results_timeOfRobotFailures[c][env][runNo] *= 100.0; #convert to percents

        #print(results_timeOfRobotFailures);
        plotFilePath = "{}/{}/timeOfRobotFailures_NR{}.png".format(constants.PLOTS_PATH, experimentNamePrefix, nrVal);
        plotFilePath = ""
        pyCreeper.crGraphs.createLinePlot(results_timeOfRobotFailures, yLabel_="% time of robot failures", markers_=markers, xTickLabels_=envs,legendLabels_=legendLabels, yMin_=0,yMax_=8, yTicksStep_=2, showAverages_=True, filePath_=plotFilePath, size_=(20, 5), gridType_=pyCreeper.crGraphs.GRID_TYPE.MAJOR, markerSize_=15, lineWidth_=0);

    if (CHECK_RESOURCE_LOST):
        #print(results_resourceLost)
        pyCreeper.crGraphs.createLinePlot(results_resourceLost, yLabel_="Resource lost", xTickLabels_=envs, showAverages_=True,legendLabels_=legendLabels, filePath_="", size_=(20, 5), gridType_=pyCreeper.crGraphs.GRID_TYPE.MAJOR, markerSize_=5, yMin_=-1,yMax_=2, lineWidth_=0);

    if (CHECK_RECRUITMENT_VS_SCOUTING):
        #print(results_resourceLost)
        pyCreeper.crGraphs.createLinePlot(results_recruitmentVsScouting, yLabel_="Recruitment / scouting", xTickLabels_=envs, showAverages_=True,legendLabels_=legendLabels, filePath_="", size_=(20, 5), gridType_=pyCreeper.crGraphs.GRID_TYPE.MAJOR, markerSize_=15, lineWidth_=0);


