IGNORE_CACHE = False;
DEBUG_OUTPUT = True;

import crData;
import constants;
from helpers import dataFormatHelpers
from helpers import helpers


def getCacheFile(cacheType_, dataPath_, numRuns_, dataPathExtraString_="", createFolder_ = False):

    folder = dataFormatHelpers.getBaseDataPath()+"/cache_"+cacheType_;
    if (constants.USING_FOOTBOTS_SIMULATION_RESULTS):
        folder = dataFormatHelpers.getBaseDataPath()+"/icrft_cache_A_"+cacheType_;

    if (createFolder_):
        helpers.createFolder(folder);

    #-- make sure that runDataPathPrefix_ is just a folder name, but include any neccessary path info
    if (constants.USING_FOOTBOTS_SIMULATION_RESULTS):
        #-- remove the containing folder of data, as it repeats in the subfolder name
        dataPath_ = dataPath_[(dataPath_.index("/")+1):];
    else:
        #-- make the containing folder a part of the file name by replacing / with _
        dataPath_ = dataPath_.replace("/","_");

    #--
    fileName = folder + "/" + dataPath_;
    if (dataPathExtraString_ != ""):
        fileName += "_" + dataPathExtraString_;
    fileName += "_" + str(numRuns_) + "runs.txt";
    return fileName;


#================================= reward totals =====================================
def cacheRewardTotals(data_, dataPath_, numRuns_):
    """
    Cache reward data (total reward or time X reward collected for multiple runs into a single file for a given scenario
    """

    if (IGNORE_CACHE):
        if (DEBUG_OUTPUT):
            print("+++++++++ Ignoring caching");
        return False;

    fileName = getCacheFile("rewardTime", dataPath_, numRuns_, createFolder_=True)

    outp = "Run\trewardTotalOrTime\n"

    for runNo in range(numRuns_):
        outp += str(runNo) + "\t"
        outp += str(data_[runNo]) + "\t"
        outp += "\n"

    with open(fileName, "w") as text_file:
        text_file.write(outp)

    if (DEBUG_OUTPUT):
        print("+++++++++ Cached reward totals to {} ".format(fileName))

def loadCachedRewardTotals(dataPath_, numRuns_):
    """
    Attempt to load reward totals for a particular scenario.

    Returns an array identical in format to that of analysis.getRunCompletionTimes
    Returns false if the cache file doesn't exist

    """
    if (IGNORE_CACHE):
        if (DEBUG_OUTPUT):
            print("+++++++++ Ignoring caching");
        return False;

    fileName = getCacheFile("rewardTime", dataPath_, numRuns_)
    if (DEBUG_OUTPUT):
        output = "+++++++++ Cache from: " + fileName;
    try:
        data = crData.fileToArray(fileName, "\t", True);
        if (DEBUG_OUTPUT):
            output += "      Loaded"
            print(output);

        #-- make the 1st column into output row
        data = crData.columnsToRows(data)[1];

        return data;
    except IOError:
        #-- the file doesn't exist
        #raise ValueError(" file {} doesn't exit ".format(fileName))
        if (DEBUG_OUTPUT):
            output += "      Not found"
            print(output);
        return False


#================================= ICR totals =====================================
def cacheICRTotals(data_, dataPath_, numRuns_, infoGainCompressionTimeInterval_):
    """
    Cache ICR data
    """

    if (IGNORE_CACHE):
        if (DEBUG_OUTPUT):
            print("+++++++++ Ignoring caching");
        return False;

    fileName = getCacheFile("costTotals", dataPath_, numRuns_,"infoSBin{}".format(infoGainCompressionTimeInterval_), createFolder_=True)

    outp = "Run\tinfoGainRate\tC_U\tC_D\td\tC_M\n"

    for runNo in range(numRuns_):
        outp += str(runNo)
        for i in range(len(data_)):
            outp += "\t" + str(data_[i][runNo])
        outp += "\n"

    with open(fileName, "w") as text_file:
        text_file.write(outp)

    if (DEBUG_OUTPUT):
        print("+++++++++ Cached ICR totals to {} ".format(fileName))


def loadCachedICRTotals(dataPath_, numRuns_, infoGainCompressionTimeInterval_):
    """
    Attempt to load reward totals for a particular scenario.

    Returns an array identical in format to that of analysis.getICRData
    Returns false if the cache file doesn't exist

    """
    if (IGNORE_CACHE):
        if (DEBUG_OUTPUT):
            print("+++++++++ Ignoring caching");
        return False;

    fileName = getCacheFile("costTotals", dataPath_, numRuns_,"infoSBin{}".format(infoGainCompressionTimeInterval_))
    if (DEBUG_OUTPUT):
        output = "+++++++++ Cache from: " + fileName;
    try:
        data = crData.fileToArray(fileName, "\t", True);
        if (DEBUG_OUTPUT):
            output += "      Loaded"
            print(output);

        #-- make the individual columns (i.e. different costs) into rows
        data = crData.columnsToRows(data)

        #-- make sure the return format of the data is correct
        if (constants.USING_FOOTBOTS_SIMULATION_RESULTS):
            #return [data[6], data[1], data[2], data[5], data[3]]
            return [data[1], data[2], data[3], data[4], data[5]]
        else:
            return [data[1], data[2], data[3], data[4], data[5]]

    except IOError:
        #-- the file doesn't exist
        if (DEBUG_OUTPUT):
            output += "      Not found"
            print(output);
        return False



#================================= ICR secondary totals =====================================
def cacheICRSecondaryTotals(data_, dataPath_, numRuns_):
    """
    Cache ICR data
    """

    if (IGNORE_CACHE):
        if (DEBUG_OUTPUT):
            print("+++++++++ Ignoring caching");
        return False;

    fileName = getCacheFile("icrSecondaryTotals", dataPath_, numRuns_, createFolder_=True)

    outp = "Run\tavgUnemploymentRate\tavgUnevenSpreadRate\tavgForagingTripTime\tavgWorksiteDiscoveryTime\n"

    for runNo in range(numRuns_):
        outp += str(runNo)
        for i in range(len(data_)):
            outp += "\t" + str(data_[i][runNo])
        outp += "\n"

    with open(fileName, "w") as text_file:
        text_file.write(outp)

    if (DEBUG_OUTPUT):
        print("+++++++++ Cached ICR secondary totals to {} ".format(fileName))


def loadCachedICRSecondaryTotals(dataPath_, numRuns_):
    """
    Attempt to load reward totals for a particular scenario.

    Returns an array identical in format to that of analysis.getICRData
    Returns false if the cache file doesn't exist

    """
    if (IGNORE_CACHE):
        if (DEBUG_OUTPUT):
            print("+++++++++ Ignoring caching");
        return False;

    fileName = getCacheFile("icrSecondaryTotals", dataPath_, numRuns_)
    if (DEBUG_OUTPUT):
        output = "+++++++++ Cache from: " + fileName;
    try:
        data = crData.fileToArray(fileName, "\t", True);
        if (DEBUG_OUTPUT):
            output += "      Loaded"
            print(output);

        #-- make the individual columns (i.e. different costs) into rows
        data = crData.columnsToRows(data)

        return [data[1],data[2],data[3], data[4]];

    except IOError:
        #-- the file doesn't exist
        if (DEBUG_OUTPUT):
            output += "      Not found"
            print(output);
        return False