#!/usr/bin/env python3

"""Clean script

Usage:
  clean.py -d <baseDir>

Options:
  -h --help                  help
  --version                  version of the script
  -d --baseDir = base_dir    directory where we will fetch the different data
"""

import os
from docopt import docopt
from tqdm import tqdm
import src.re_number as rnb
import src.manage_io as mio


if __name__ == '__main__':
    BASE_DIR = docopt(__doc__, version='0.1')["--baseDir"]
    log_name = "clean.log"
    path_to_log = BASE_DIR + log_name

    with open(BASE_DIR + "Data/METAFOLD.list", 'r') as metafold_file:
        FILES_TO_TAKE = mio.parse_metafold_list(metafold_file)

    if os.path.isfile(path_to_log):
        os.remove(path_to_log)

    # Create a file anyway (empy if everything went fine for cleaning):
    with open(path_to_log, 'w'):
        pass

    for name in tqdm(FILES_TO_TAKE):
        common_path = BASE_DIR + "Data/HOMSTRAD/" + name + '/'
        pdb_id = FILES_TO_TAKE[name]
        if os.path.isdir(BASE_DIR + "Data/HOMSTRAD/" + name):
            os.system("mv " + common_path + pdb_id +
                      ".atm " + common_path + 'origin_' +
                      pdb_id + ".atm")
            rep = rnb.re_number_pdb(1, common_path + 'origin_' + pdb_id +
                                    ".atm", common_path + pdb_id + ".atm")
            if not rep:
                os.system("rm -rf " + BASE_DIR + "Data/HOMSTRAD/" + name)
                with open(path_to_log, "a") as filout:
                    filout.write(name + "\n")
