#-*-coding:utf-8-*-
import os
import shutil
import subprocess
import time

try:
    import params as ct
    isParams = True
    verbose = False
except:
    isParams = False
    print "PARAMS NOT FOUND"
    verbose = False


if isParams:
    sshprefix = ["ssh", ct.USERNAME+"@avakas.mcia.univ-bordeaux.fr"]
    prefix = sshprefix + ["-t"]
    REMOTE = ct.REMOTE
else:
    REMOTE = False
    prefix = []


def convertCom(localCommand, prefixC=prefix, isList=True):
    concatCommand = ""
    if type(localCommand) == str:
        localCommand = [[localCommand]]
    elif type(localCommand[0]) == str:
        localCommand = [localCommand]
    for lc in localCommand:
        for c in lc:
            if concatCommand != "":
                concatCommand += " "
            concatCommand += c
        concatCommand += ";"

    concatCommand = concatCommand[:-1] # remove last ;

    if isList:
        return prefixC+[concatCommand]
    else:
        return " ".join(prefixC+["'"+concatCommand+"'"])


def launchSub(command, remote=REMOTE):
    if remote:
        cp = command.replace("\n", "\\n")
        if verbose:
            print "SUBPROCESS LAUNCHSUB CALL", cp[:100] #CARE ONLY DISPLAY 30 FIRST CHARS
        command = convertCom(command, prefix)
        #print "converted command:", command
    if verbose:
        print "command", command
    if remote:
        subprocess.call(command)  # the list split works with ssh
    else:
        subprocess.check_output(command, shell=True)# the input as one string works for local launch


def subprocess_output(com, remote=REMOTE, delay=5):
    fullcom = com
    if remote:
        if verbose and 'qstat' not in com:
            print "SUBPROCESS REMOTE OUTPUT CALL", com
        fullcom = convertCom(com, sshprefix, False)
    #print "fc", fullcom
    try:
        out = subprocess.check_output(fullcom, shell=True)
        if delay != 5: # if was not on first try, inform on success
            print "Retry successful"
        return out
    except AttributeError as e:
        print e
        print "[ERROR] Check your python version and if necessary add 'module load python/2.7.6' to your bashrc file"
    except subprocess.CalledProcessorError as e:
         print str(e.output)
         print "[WARNING] Retry in "+str(delay)+" seconds..."
         time.sleep(delay)
         delay = min(600, delay*2)
         return subprocess_output(com, remote, delay)


def listContent(pat, remote=REMOTE):
    files = subprocess_output("ls -m "+pat, remote)
    files = files.replace("\n", " ")
    if files[-1] == " ":
        files = files[:-1]
    return files.split(", ")


def removeContent(pat, isfile=True, remote=REMOTE):
    if isfile:
        launchSub("rm "+pat)
    else:# if folder
        #print "FOLDER REMOVE NOT IMPLEMENTED"
        yn = "y"#raw_input("Do you really want to del "+pat+"? (y/n) ")
        if yn in "Yy":
            launchSub("rm -r "+pat)


def asymetricCopy(origin, dest, isfile=True, remote=REMOTE):
    """for copy between local and avakas when remote"""
    if remote:
        begin = ["scp"]
        if not isfile:
            begin += ["-r"]
        print "origdest", origin, ">", dest#REMOTE_BASE+
        subprocess.call(begin + [origin, "athoni@avakas.mcia.univ-bordeaux.fr:"+dest]) #+REMOTE_BASE
        #TODO ADD PREFIX REMOTE?, cut mtp path?
    else:
        if isfile:
            shutil.copyfile(origin, dest)
        else:
            shutil.copytree(origin, dest)


def readFile(pat, remote=REMOTE, prefix="", onlyTail=False): #care with path prefix for remote
    if remote:
        patAbs = pat
        if prefix != "":
            patAbs = prefix +"/"+ pat
        readCommand = 'cat'
        if onlyTail:
            readCommand = 'tail'
        sshl = subprocess_output([readCommand, patAbs])
        lf = sshl.split("\n")
        #print "ssh read", lf
    else:
        f = open(pat, "r")
        lfsource = f.readlines()
        f.close()
        lf = []
        for l in lfsource:
            lf += [l.rstrip()] #remove \r & \n
        if verbose:
            print "Reading", pat, lf[-2:]
    return lf

def writeFile(pat, content, isScript=False, remote=REMOTE):
    if verbose:
        print "WRITING FILE", pat
    if remote:
        txtWrite = 'echo "'+content+'" >> ' + pat  # CARE ADD DATA, NO RESET
        if isScript:
            txtWrite += "; chmod 755 " + pat
        launchSub(txtWrite)
    else:
        fs = open(pat, "w")
        fs.write(content)
        fs.close()
        if isScript:
            os.chmod(pat, 0755)

def checkFilePresence(pat, isfolder=False, remote=REMOTE):
    if remote:
        optionSearch = "-f"
        if isfolder:
            optionSearch = "-d"
        getPresence = subprocess_output('if [ '+optionSearch+' '+pat+' ]; then echo "found"; else echo "niet"; fi')
        if "found" in getPresence:
            return True
        elif "niet" in getPresence:
            return False
        else:
            print "[BUG] OUTPUT TROUBLE with check remote file presence"
            return False
    else:
        return os.path.isfile(pat)

# test if remote_reg folder exists
def createFolder(pat, remote=REMOTE):
    if remote:
        getPresence = subprocess_output('if [ -d '+pat+' ]; then echo "found"; else echo "niet";mkdir -p ' + pat + '; fi')
        #print "PREZ", getPresence
        if "found" not in getPresence:
            if verbose:
                print "[INFO] REMOTE dir created."
            return True
        else:
            if verbose:
                print "[WARNING] REMOTE dir already exists. Could be a problem."
            return False
    else:
        os.makedirs(pat)


def moveAndLaunchScript(path, script="", remote=REMOTE):
    if remote:
        commands = ["cd "+path]
        if script != "":
            commands += ["sh "+script]
            launchSub(commands) #TODO check if ; is correctly added
    else:
        os.chdir(path)
        if script != "":
            subprocess.call(["sh", script])

if __name__=="__main__":
    a = readFile("/scratch/athoni/TEST1.rout")
    print a
    #b = readFile("./TEST1.rout", prefix=REMOTE_BASE)
    #print b
    print listContent("~", remote=True)
    print listContent("~", remote=False)
    #print readFile("/scratch/athoni/TEST1.rout", remote=True)
    #print readFile("/home/armel/Summary_qtl", remote=False)
    writeFile("/home/athoni/WF2.txt", "TEST\n1\n2", isScript=True)


#com = [["mkdir", "X12"], ["echo", "43"], ["mkdir", "X22"]]
#import subprocess
#for c in com:
#    subprocess.call(c)
#distCom = convertCom(com)
#print distCom
#subprocess.call(prefix+[distCom])
