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

import subprocess
import time
import os
import fileManip as FM

import remotePipeline as RP

# The Cruncher will look in the output folders to treat every genesXX.csv he can find (and delete them if the Killer option is activated)
# Don't forget to keep a track of treated files in an external log file


#amorce = "cd ../treatment/R_scripts\n"

#TODO: unify arg structure with trait then loci
def getRCmd(inDir, outDir, selectedLoci="", step=1, species="S1", mode="G", trait="", ltype=""):
    rcmd = ""
    if mode == "G":
        rcmd = "R CMD BATCH --no-save --no-restore '--args " + " ".join(
            [species, str(step), inDir, trait, selectedLoci]) + "' r_analysis_genet.r /dev/stdout > " + outDir + "\n"
    elif mode == "Pmc":
        if type(trait) == list:
            #return "R CMD BATCH --no-save --no-restore '--args " + " ".join([species, str(step), inDir, selectedLoci]) + " "+" ".join([i+"-pheno" for i in trait]) + " ' r_analysis_multicar.r /dev/stdout > " + outDir + "\n"
            rcmd = "R CMD BATCH --no-save --no-restore '--args " + " ".join(
                [species, str(step), inDir]) + " " + " ".join(
                [i + "-pheno" for i in trait]) + " ' r_analysis_multicar.r /dev/stdout > " + outDir + "\n"
        else:
            print "can't run Pmc since trait is not a list :", trait
    elif mode == "Plt":
        rcmd = "R CMD BATCH --no-save --no-restore '--args " + " ".join(
            [species, str(step), inDir, trait]) + "-pheno" + " ' r_analysis_ltype_quanti.r /dev/stdout > " + outDir + "\n"
    else:
        rcmd = "R CMD BATCH --no-save --no-restore '--args " + " ".join([species, str(step), inDir, selectedLoci, trait]) + "-pheno" + " ' r_analysis_quanti.r /dev/stdout > " + outDir + "\n"
    if rcmd != "":
        #print "RCMD", rcmd
        return rcmd

def generateAllRLauncher(allCalls, path="."):
    parallel = True
    suffix = "\n"
    if parallel:
         suffix = " &" + suffix
    txt = ""
    for c in allCalls:
        txt += "source " + c + suffix
    RP.writeFile(path+"/triggerAllR_emergencyCall.sh", txt+"\nwait\n", isScript=True)


def generateMultiRLauncher(scriptName, toLaunch, newamorce=""):
    parallel = True
    verbose = True
    suffix = "\n"
    if parallel:
         suffix = " &"+suffix
    if verbose:
        suffix = ' ; echo "' + scriptname + '"' + suffix
    #fs = open(scriptName, "w")
    txtMulti = newamorce + "\n"
    for s in toLaunch:
        job, launcher = s
        txtMulti += "source " + launcher +suffix
    #fs.write(txtMulti+"\nwait\n")
    #fs.close()
    #os.chmod(scriptName, 0755)
    RP.writeFile(scriptName, txtMulti+"\nwait\n", isScript=True)

def generateMonoRLauncher(scriptName, inDir, outDir, selectedLoci="", step=1, species="S1", mode="G", trait="", newamorce="", ltype=""):
    #fs = open(scriptName, "w")
    #fs.write(newamorce + getRCmd(inDir, outDir, selectedLoci, step, species, mode, trait, ltype))
    #fs.close()
    #os.chmod(scriptName, 0755)
    content = newamorce + getRCmd(inDir, outDir, selectedLoci, step, species, mode, trait, ltype)
    RP.writeFile(scriptName, content, isScript=True)


regDir = "./Zi8362"
treatDir = "../treatment/"
regFromRscript = "../../SIMUWRAPPER/NonReg/"  # UGLY, use absolute path...


def getLociList(csvPath, absol=False, trait = "T1", mode="classic", splitLt=False):
    print "csv", csvPath
    if csvPath[-1] == "\n":
        csvPath = csvPath[:-1]
    if mode=='standalone':
        #print "standalone"
        T1f = "/".join(csvPath.split("/")[:-2] + ["settings/user_input/traits/"+trait+".lua"])
        #print "STANDALONE", T1f
    else:
        if absol:
            if trait+".lua" not in csvPath:
                if "outputs" in csvPath:
                    T1f = "/".join(csvPath.split("/")[:-3] + ["user_input/traits/"+trait+".lua"])
                else:
                    #T1f = "/".join(csvPath.split("/")[:-1] + [trait+".lua"])  # + "T1.lua"
                    T1f = csvPath + "/MTP/user_input/traits/"+trait+".lua"  # + "T1.lua"
                #print "t1f", T1f
            else:
                #print "keep val"
                T1f = csvPath
        else:
            T1f = "/".join(csvPath.split("/")[:3] + [trait+".lua"])
    #try:
        #f = open(T1f, "r")
        #l = f.readlines()
        #f.close()
    l = RP.readFile(T1f)
    #except:
    #    print "File", T1f, "not present (or readfile function bug). Stat computation cancelled"
    #    return False
    flagLT = False
    """flagA = False
    flagB = False
    txtLoci = ""
    for li in l:
        if not flagLT:
            if li[:6] == "ltypes":
                flagLT = True
        else:
            li2 = li.replace(" ", "")
            if li2[:6] == 'id="a"':
                flagA = True
            elif li2[:3] == 'id=':
                flagA = False
            elif li2[:9] == "lociList=" and flagA:
                return li2[li2.find("{") + 1:li2.find("}") - 1]
    print "Loci list not found"
    return []"""


    flagA = False
    flagB = False
    txtLoci = ""
    for li in l:
        if not flagLT:
            if li[:6] == "ltypes":
                flagLT = True
        else:
            li2 = li.replace(" ", "")
            if li2[:6] == 'id="a"':
                flagA = True
                flagB = False
            elif li2[:6] == 'id="b"':
                flagA = False
                flagB = True
                if splitLt:
                    if txtLoci[-1] == ",":
                        txtLoci = txtLoci[:-1]
                    txtLoci += ";"
            elif li2[:3] == 'id=':
                flagA = False
                flagB = False
            elif li2[:9] == "lociList=" and (flagA or flagB):
                txtLoci += li2[li2.find("{") + 1:li2.find("}")]
                if txtLoci[-1] not in [",", ";"]:
                    txtLoci += ","
    if txtLoci != "":
        txtLoci = txtLoci[:-1]
        return txtLoci
    print "Loci list not found"
    return []

#def getLtypeList(csvPath, absol=False, trait = "T1", mode="classic"):


def getLociDict(csvPath, traits, absol=False):
    dTrait = {}
    for t in traits:
        dTrait[t] = getLociList(csvPath, absol, t)
    return dTrait
