from __future__ import print_function
from os import sep, rename as mv
import biotools.IO as io
import biotools.analysis.options as options

try:
    get_input = raw_input
except:
    get_input = input


def rename(direc, db, files):
    '''
    This isn't really for bioinformatics, this is more for the pipeline, to
    rename the files generated by cluster.py with a little human interaction.
    '''

    names = []
    seqdb = dict((s.name, s) for s in io.open(db, 'r'))
    nt_dir, aa_dir = direc + 'nt' + sep, direc + 'aa' + sep
    for f in files:
        seq = io.open(nt_dir + f, 'r').next()
        ids = seq.defline.split(', ')
        print("File\033[33;1m", f, \
              "\033[0mis described by the following sequences:")
        try:
            for id in ids:
                seqdb[id]
                print("* " + seqdb[id].name + ': ' +
                      seqdb[id].defline.split('[')[0])
        except KeyError:
            print("* (none)")
            continue
        pre = get_input("\033[33;1mWhat should we call this file " +
                        "(or hit enter to skip)? \033[0m")
        fpre = f[:f.find('.')]

        if pre != "":
            count = 0
            while True:
                rpre = pre + ((" (%d)" % count) if count > 0 else "")
                try:
                    fh = open(nt_dir + rpre + ".fasta", 'r')
                    fh.close()
                    count += 1
                    continue
                except IOError:
                    nt_old, nt_new = nt_dir + fpre, nt_dir + rpre
                    aa_old, aa_new = aa_dir + fpre, aa_dir + rpre
                    print("Renaming " + fpre + ".* to " + rpre + ".*")
                    try:
                        mv(nt_old + ".fasta", nt_new + ".fasta")
                        mv(aa_old + ".fasta", aa_new + ".fasta")
                        mv(nt_old + ".clustalw", nt_new + ".clustalw")
                        mv(aa_old + ".clustalw", aa_new + ".clustalw")
                        names.append(nt_new + '.clustalw')
                        names.append(aa_new + '.clustalw')
                    except OSError:
                        pass
                    break
    return names
