# -*-coding:utf-8-*-

import shutil

import subprocess
import time
import os
import random
#import simuParams as lct
import fileManip as FM

import remotePipeline as RP

verbose = False 

def switchUserInput(testNumber, MTPdir="../METAPOP", originSfol = ""):
    targetSFile = "S1_Test" + str(testNumber) + ".lua"

    print "MTPD", MTPdir
    if originSfol == "":
        originSfol = "TestUserInputFiles/"
    originS = originSfol + targetSFile

    #check associated Traits files
    corresT = FM.checkTfromS(originS)
    print "CT", corresT

    RP.asymetricCopy(originS, MTPdir + "/user_input/species/S1.lua", remote=False)
    for trait in corresT:
        targetTFile = trait + "_Test" + str(testNumber) + ".lua"
        RP.asymetricCopy(originSfol + targetTFile, MTPdir + "/user_input/traits/"+trait+".lua")
        if MTPdir != "../METAPOP":
            asymetricCopy(originSfol + targetTFile, MTPdir + "/../../"+trait+".lua")

    if "../METAPOP" not in MTPdir:
        RP.asymetricCopy(originS, MTPdir + "/../../S1.lua")


def compileBin(MTPdir="../METAPOP", regDir="../SIMUWRAPPER/NonReg", isRedirect=True):
    #CHECK COMPILATION EFFICIENCY
    isBefore = checkBin(MTPdir, doRecomp=False)

    RP.moveAndLaunchScript(MTPdir, remote=False)
    #print "CWD", os.getcwd()

    # shutil.copyfile(backupDir+"metapop", binPath+"metapop")
    isAfter = checkBin(MTPdir, doRecomp=False)

    if not isAfter:
        print "Compilation failed."

    if isRedirect:
        RP.moveAndLaunchScript(regDir, remote=False)
        time.sleep(7)#necessary?


def checkBin(MTPdir="../METAPOP", doRecomp=True, standalone=False):
    #print "OSC", os.getcwd()
    if standalone:
        binPath = "sources/bin/"
    else:
        binPath = MTPdir + "/sources/bin/"
    isBin = RP.checkFilePresence(binPath + "metapop") or RP.checkFilePresence(binPath + "metapop.exe")
    if not isBin and doRecomp:
        print "\tBin not present, need recompilation"
        #print "CWD CB", os.getcwd()
        if standalone:
            compileBin(MTPdir=".", isRedirect=False)
        else:
            compileBin(MTPdir, os.getcwd()) #care, what happens for REMOTE case?
    if not doRecomp:
        return isBin


#mainPath = os.getcwd()
#isRandomSeed = lct.IS_RANDOM_SEED
#isRandomSeedInit = lct.IS_RANDOM_SEED_INIT #TODO : RECAST THIS BOOLEAN
seedConf = 42
#def switchConfFile(outputDir, confPath='../METAPOP/user_input/conf.lua', isReg=True, isRand=isRandomSeed, isRandInit=isRandomSeedInit):
def switchConfFile(outputDir, confPath='../METAPOP/user_input/simuConf.lua', isReg=True):
    lf = RP.readFile(confPath, remote=False)
    ft2 = ""
    lineToAdd = "outputDir = '" + outputDir + "/'\n"
    oldDir = ""
    nSteps = ""

    IS_RANDOM_SEED = True
    IS_RANDOM_SEED_INIT = True
    for l in lf:
        if "outputDir" in l:
            ft2 += lineToAdd
            oldDir = l.split("=")[1]
        #elif l[:8] == "saveStep":
        #    if not isReg:
        #        ft2 += l[:8] + " = "+str(lct.SAVE_STEPS)+"\n"
        #    else:
        #        ft2 += l
        elif l[:12] == "isRegression":
            if isReg:
                ft2 += l[:12] + " = true\n"
            else:
                ft2 += l[:12] + " = false\n"
        else:
            # get value, no change in line
            if "simLength" in l:
                nSteps = l.split("=")[-1]#[:-1]
            elif "IS_RANDOM_SEED_INIT" in l and "false" in l.split("=")[1]:
                IS_RANDOM_SEED_INIT = False
            elif "IS_RANDOM_SEED" in l and "false" in l.split("=")[1]:
                IS_RANDOM_SEED = False
            ft2 += l + "\n"
    #print "RANDOM IN SWITCH", IS_RANDOM_SEED_INIT, "&", IS_RANDOM_SEED
    if oldDir == "":
        if verbose:
            print "outputDir was not specified. Newly generated:", lineToAdd
        ft2 += lineToAdd
    else:
        if verbose:
            print "outPutDir has been changed from", oldDir, "to", outputDir
    #g = open(confPath, 'w')
    #g.write(ft2)
    #g.close()
    RP.writeFile(confPath, ft2, remote=False)

    seedPath = "/".join(confPath.split("/")[:-1]+["seed.lua"])
    lf = RP.readFile(seedPath, remote=False)
    ft2 = ""

    for l in lf:
        if l[:4] == "seed":
            if IS_RANDOM_SEED or IS_RANDOM_SEED_INIT:  # rand and randinit are taken from simuParams if local or NonReg/params if distant
                lseedword = len(l.split("=")[0])
                if 'init' not in l or IS_RANDOM_SEED_INIT:
                    ft2 += l[:lseedword + 1] + " " + str(random.randrange(1000)) + "\n"
                else:
                    ft2 += l
            else:
                lseedword = len(l.split("=")[0])
                ft2 += l[:lseedword + 1] + " " + str(seedConf) + "\n"
        else:
            ft2 += l + "\n"
    #g = open(seedPath, 'w')
    #g.write(ft2)
    #g.close()
    RP.writeFile(seedPath, ft2, remote=False)

    return nSteps

def checkIndFiles(indDir, nreplicates):
    isIteration = False
    lInd = []
    if RP.checkFilePresence(indDir, isfolder=True):
        for the_file in RP.listContent(indDir, remote=False):
            if the_file[:4] == "ind_" and the_file[-4:] == ".txt" and the_file[4:-4].isdigit():
                lInd += [int(the_file[4:-4])]
            else:
                print the_file, "ignored"
        if len(lInd) == nreplicates:
            isIteration = True
    else:
        print "NO IND DIR FOUND, use ind.txt"
    lInd.sort()
    print "IND FILES", isIteration, lInd
    return isIteration, lInd

"""
def newMeta(metaName="MS", nbRepet=2, scenars=[1, 2, 3], suffix="", MTPduplication=False):
    nbScenars = len(scenars)
    metaPath = os.path.join(mainPath, metaName + str(nbScenars) + "_" + str(nbRepet) + "_" + suffix)
    os.makedirs(metaPath)
    print "* METASIMU : " + str(nbScenars) + "_" + str(nbRepet) + "_" + suffix + " *"
    shutil.copyfile("../METAPOP/sources/bin/metapop", metaPath + "/metapop")
    for i in scenars:
        # L0 = getTestParams(i)
        # print L0
        # setMTPParams(L0)
        print " ==== Params", i, "===="
        switchUserInput(i)

        # generates the output folder
        dirName = "Scenar" + str(i)
        scenarDir = os.path.join(metaPath, dirName)
        os.makedirs(scenarDir)
        # (copy conf files into output folder)
        shutil.copyfile("../METAPOP/user_input/species/S1.lua", scenarDir + "/S1.lua")
        shutil.copyfile("../METAPOP/user_input/traits/T1.lua", scenarDir + "/T1.lua")

        # launch metaSimu via subprocess
        for r in range(1, nbRepet + 1):
            print "\t == Repet", r, "=="
            outputFolder = os.path.join(scenarDir, "R" + str(r))
            os.makedirs(outputFolder)
            dfPath = {}
            for f in ["settings", "genotypes", "quantitative"]:
                dfPath[f] = os.path.join(outputFolder, f)
                os.makedirs(dfPath[f])

            # CREATE A DUPLICATION OF THE MTP WORKSPACE FOR EACH REPLICATION
            confPath = '../METAPOP/user_input/simuConf.lua'
            # BLA REPLICATION

            switchConfFile(outputFolder, confPath)
            # need creation of "raw_input" folder ?
            shutil.copyfile(confPath, dfPath["settings"] + "/simuConf.lua")
            time.sleep(10)
            # print "more1"
            # subprocess.call(["more",confPath])
            # time.sleep(20)
            # print "more2"
            # subprocess.call(["more",confPath])
            checkBin()
            # subprocess.call(["sh", "triggerSimu.sh"])#, outputFolder])

            #p = os.path.join(outputFolder, "MTP", "outputs")
	    #print("path to delete:"+p)
            #shutil.rmtree(p)

            jobRef = "MTP" + suffix + "_" + str(i) + "." + str(r)

            # delete replicate outputs here?
            shutil.rmtree(os.path.join(outputFolder, "MTP", "outputs"))

            subprocess.call(["sh", "triggerSimu.sh", jobRef])  # , outputFolder])
            ##checkLaunchState(jobRef)
            # subprocess.call(["sh", "triggerLight.sh"])
            # add an option with output redirection
            time.sleep(20)  # 0
        if i < nbScenars:
            time.sleep(30)  # 45 #temporary solution to avoid business of script file ?"""


"""if __name__ == "__main__":
    import random

    nrep = int(raw_input("nb repetitions? "))
    scenarB = int(raw_input("First scenar to run? "))
    scenarE = int(raw_input("Last scenar to run? "))

    newMeta("medMS", nrep, range(scenarB, scenarE + 1), suffix="V11." + str(random.randrange(1000)))
"""
