import subprocess
import sys
import time

#import NonReg.params as ct
#username = ct.USERNAME
import remotePipeline as rP

def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

def getSpecies(inputFolder, remote=False): #sure about that file as reference?
    #f = open(inputFolder+"/.struct/species_index.txt")
    #l = f.readlines()
    #f.close()
    l = rP.readFile(inputFolder+"/.struct/species_index.txt", remote=remote)

    species = []
    for li in l:
        if "species/" in li:
            species += [li.split("/")[-1][:-4]]
    return species

def getReplicationsNumber(confFile, remote=False):
    replications = 1
    # get values
    lf = rP.readFile(confFile, remote=remote) #TODO need check path

    for l in lf:
        if "REPLICATIONS" in l and "=" in l:
            replications = int(l.split("=")[1])
    return replications


def checkTfromS(nf, remote=False):
    lf = rP.readFile(nf, remote=remote) #TODO need check path
    traitsRaw = []
    for l in lf:
        if "traitsId" in l:
            lnocomment = l.split("==")[0]
            traitsRaw = lnocomment.split("{")[1][:-1].split(",") # :-1 = remove last "
            #print "traitsraw", traitsRaw
    traits = []
    for t in traitsRaw:
            bT = t.find("T")
            eT = t.find('"', bT)
            traits.append(t[bT:eT])
    if traits != []:
        #print "traits", traits
        return traits
    print "No traitsId line in file", nf, "."
    exit(0)

def checkLTfromT(nf, remote=False):
    lf = rP.readFile(nf, remote=remote) #TODO need check path
    ltypesRaw = []
    currentId = ""
    for l in lf:
        if len(l.split()) > 0 and l.split()[0][:2] != "--":
            if "id =" in l or "id=" in l:
                if '"a"' in l or "'a'" in l:
                    currentId = "a"
                elif '"b"' in l or "'b'" in l:
                    currentId = "b"
                elif '"c"' in l or "'c'" in l:
                    currentId = "c"
                #else:
                #    print 'id not recognized (can be "a", "b" or "c"):', currentId
            elif ("phi=" in l or "phi =" in l) and not ("0," in l or "0 ," in l):
                ltypesRaw += [currentId]
    #print nf,ltypesRaw
    return ltypesRaw


def parseQstat(username):
    #p = subprocess.Popen(["qstat", "-u", username], stdout=subprocess.PIPE)
    #out, err = p.communicate()
    out = "BUG"
    tests = 0
    error = ""
    deltat = 1
    while tests < 3 and out == "BUG":
        tests += 0 #1
        try:
            #print "test out"
            out = rP.subprocess_output("qstat -u "+username) # TODO check if working
            #print "test out done"
        except:
            error2 = sys.exc_info()[0]
            if deltat == 1:
                print "-- CATCHED --", error2
            print "[Warning] qstat call failed, retry in "+str(deltat)+' seconds...'
            time.sleep(deltat)
            deltat = min(600, deltat*2)
    #time.sleep(60*60*24)
    #out = rP.subprocess_output("qstat -u " + username)

    #print "QSTAT:", out.split("\n")
    dJobname = {}
    #for l in out.split("\n"):
    for l in out.split("\n"):
        if username in l:
            ls = l.split()
            dJobname[ls[0]] = (ls[3], ls[9])
    #print "DJ",dJobname
    return dJobname


def shfunc(comd, filename, remote):
    out =  rP.subprocess_output(comd + " " + filename, remote=remote) # TODO check if working
    return out


def checkInput(MTPrep = "../METAPOP", remote=False):
    #get value of S in user input
    lst = []
    locS = "species/S1.lua"
    traits = checkTfromS(MTPrep + "/user_input/"+locS, remote=remote)

    fst = [locS] + ["traits/"+t+".lua" for t in traits]
    print "FST", fst
    for nf in fst:
        #f = open(MTPrep + "/user_input/"+nf, "r")
        lf = rP.readFile(MTPrep + "/user_input/"+nf, remote=remote)
        for l in lf:
            if "--S" in l:
                try:
                    lst += [int(l[l.find("--S")+3:])]
                except:
                    print "Value --S not found or not number"
                    return []
                break
    if len(lst)==len(fst):
        if max(lst) == min(lst):
            return lst[0]
        else:
            print "INPUT DISCREPENCY : SorT", min(lst),  "VS SorT", max(lst)
    return []

def getCsvName(routFile, remote):
    #f = open(routFile)
    #lf = f.readlines()
    #f.close()
    lf = rP.readFile(routFile, remote=remote)  # TODO check if working
    for l in lf:
        if "CSVF" in l and "[1]" in l:
            return l.split(" ")[2][:-2]
    return ""


def checkOutdir(MTPrep = "../METAPOP", remote=False):
    confile = MTPrep + "/user_input/simuConf.lua"
    #f = open(confile, "r")
    #lf = f.readlines()
    #print "DBG:COD",confile
    #f.close()
    lf = rP.readFile(confile, remote=remote)  # TODO check if working
    for l in lf:
        if "outputDir" in l:
            ls = l.split("/")
            #print "oDd",ls
            return (int(ls[-3][6:]), int(ls[-2][1:]))
    print lf
    print "No outputDir in simuConf.lua !?"
    return ()

def getScInput(outfile, remote):
    lrez = shfunc("head", outfile, remote=remote)
    numL = -1
    for l in lrez.split("\n"):
        if "--S" in l:
            numL = int(l[l.find("--S")+3:])
    return numL

def parseAgeCsv(filepath, splitAge=True, remote=False, prefix=""):
    #if filepath[-1]=="\n":
    #    filepath=filepath[:-1]
    filepath = filepath.rstrip()
    #f = open(filepath, "r")
    #lf = f.readlines()
    #f.close()
    lf = rP.readFile(filepath, remote=remote, prefix=prefix)
    nByPop = {}
    for l in lf:
        ls = l.split(" ")
        if "\n" in l:
            ls = l[:-1].split(" ")

        if len(ls) == 3:
            pop, ind, age = ls
        if pop not in nByPop:
            if splitAge:
                nByPop[pop] = {}
            else:
                nByPop[pop] = 0
        if splitAge:
            if age not in nByPop[pop]:
                nByPop[pop][age] = 0
            nByPop[pop][age] += 1
        else:
            nByPop[pop] += 1
    return nByPop
