# Path: targetexplorer/pdb.py
# class GatherPDB(object):
#     def __init__(self, structure_dirs=None, run_main=True, commit_to_db=True):
#         self.commit_to_db = commit_to_db
#         if type(structure_dirs) == str:
#             self.structure_dirs = [structure_dirs]
#         else:
#             self.structure_dirs = structure_dirs
# 
#         if run_main:
#             self.main()
# 
#     def main(self):
#         external_data_dir = os.path.join('external-data')
#         local_pdb_dir = os.path.join(external_data_dir, 'PDB')
#         local_sifts_dir = os.path.join(external_data_dir, 'SIFTS')
#         if not os.path.exists(local_pdb_dir):
#             os.mkdir(local_pdb_dir)
#         if not os.path.exists(local_sifts_dir):
#             os.mkdir(local_sifts_dir)
# 
#         now = datetime.datetime.utcnow()
# 
#         # get current crawl number
#         crawldata_row = models.CrawlData.query.first()
#         current_crawl_number = crawldata_row.current_crawl_number
#         print 'Current crawl number: %d' % current_crawl_number
# 
#         verbose = False
# 
#         # ====================
#         # Main
#         # ====================
# 
#         # first get a list of PDB rows from the db
#         db_pdb_rows = models.PDBEntry.query.filter_by(crawl_number=current_crawl_number).all()
# 
#         # prepare a dict for each PDB row to be passed to the function extract_pdb_data
#         db_pdb_dicts = []
#         for pdb_row in db_pdb_rows:
#             db_entry = models.DBEntry.query.filter_by(id=pdb_row.db_entry_id).first()
#             uniprot_row = db_entry.uniprot.first()
#             canon_isoform_row = db_entry.uniprot_isoforms.filter_by(is_canonical=True).first()
#             chain_data = [
#                 {
#                     'chain_row_id': chain_row.id,
#                     'chain_id': chain_row.chain_id
#                 } for chain_row in pdb_row.chains
#             ]
#             pdb_dict = {
#                 'pdb_row_id': pdb_row.id,
#                 'pdb_id': pdb_row.pdb_id,
#                 'ac': uniprot_row.ac,
#                 'entry_name': uniprot_row.entry_name,
#                 'seq': canon_isoform_row.sequence,
#                 'chain_data': chain_data,
#                 'structure_dirs': self.structure_dirs
#             }
#             db_pdb_dicts.append(pdb_dict)
# 
#         # TODO multiprocessing is causing problems with tests. Maybe refactor to use mpi4py instead?
#         # Use multiprocessor pool to retrieve various data for each PDB
#         # pool = Pool()
#         results = map(extract_pdb_data, db_pdb_dicts)
# 
#         for pdb_results in results:
#             pdb_row_id = pdb_results['pdb_row_id']
#             pdb_row = models.PDBEntry.query.filter_by(id=pdb_row_id).first()
# 
#             if 'exception_message' in pdb_results and pdb_results.get('exception_message') == 'SIFTS file could not be downloaded':
#                 db.session.delete(pdb_row)
#                 continue
# 
#             for chain_row_id in pdb_results['chain_dicts']:
#                 chain_row = models.PDBChain.query.filter_by(id=chain_row_id).first()
#                 chain_dict = pdb_results['chain_dicts'][chain_row_id]
#                 for key in chain_dict:
#                     if key in ['chain_id', 'exception_message']:
#                         continue
#                     setattr(chain_row, key, chain_dict[key])
# 
#                 # Delete chain entries with exception message of 'DELETE_ME'.
#                 # These are cases where the sifts_uniprotAC does not match the
#                 # uniprotAC in DB_root (derived from the UniProt entry by
#                 # gather-uniprot.py), or where more than 90% of the
#                 # experimental sequence is unobserved
#                 if chain_dict['exception_message'] == 'DELETE_ME':
#                     db.session.delete(chain_row)
# 
#             # If all chain entries have been deleted, delete the entire PDB row.
#             if pdb_row.chains.count() == 0:
#                 db.session.delete(pdb_row)
# 
#         current_crawl_datestamp_row = models.DateStamps.query.filter_by(crawl_number=current_crawl_number).first()
#         current_crawl_datestamp_row.pdb_datestamp = now
#         if self.commit_to_db:
#             db.session.commit()
#         print 'Done.'


import argparse
from targetexplorer.pdb import GatherPDB


argparser = argparse.ArgumentParser(description='Gather cBioPortal data')
argparser.add_argument(
    '--nocommit',
    help='Run script, but do not commit to database.',
    action='store_true',
    default=False

# Path: targetexplorer/pdb.py
# class GatherPDB(object):
#     def __init__(self, structure_dirs=None, run_main=True, commit_to_db=True):
#         self.commit_to_db = commit_to_db
#         if type(structure_dirs) == str:
#             self.structure_dirs = [structure_dirs]
#         else:
#             self.structure_dirs = structure_dirs
# 
#         if run_main:
#             self.main()
# 
#     def main(self):
#         external_data_dir = os.path.join('external-data')
#         local_pdb_dir = os.path.join(external_data_dir, 'PDB')
#         local_sifts_dir = os.path.join(external_data_dir, 'SIFTS')
#         if not os.path.exists(local_pdb_dir):
#             os.mkdir(local_pdb_dir)
#         if not os.path.exists(local_sifts_dir):
#             os.mkdir(local_sifts_dir)
# 
#         now = datetime.datetime.utcnow()
# 
#         # get current crawl number
#         crawldata_row = models.CrawlData.query.first()
#         current_crawl_number = crawldata_row.current_crawl_number
#         print 'Current crawl number: %d' % current_crawl_number
# 
#         verbose = False
# 
#         # ====================
#         # Main
#         # ====================
# 
#         # first get a list of PDB rows from the db
#         db_pdb_rows = models.PDBEntry.query.filter_by(crawl_number=current_crawl_number).all()
# 
#         # prepare a dict for each PDB row to be passed to the function extract_pdb_data
#         db_pdb_dicts = []
#         for pdb_row in db_pdb_rows:
#             db_entry = models.DBEntry.query.filter_by(id=pdb_row.db_entry_id).first()
#             uniprot_row = db_entry.uniprot.first()
#             canon_isoform_row = db_entry.uniprot_isoforms.filter_by(is_canonical=True).first()
#             chain_data = [
#                 {
#                     'chain_row_id': chain_row.id,
#                     'chain_id': chain_row.chain_id
#                 } for chain_row in pdb_row.chains
#             ]
#             pdb_dict = {
#                 'pdb_row_id': pdb_row.id,
#                 'pdb_id': pdb_row.pdb_id,
#                 'ac': uniprot_row.ac,
#                 'entry_name': uniprot_row.entry_name,
#                 'seq': canon_isoform_row.sequence,
#                 'chain_data': chain_data,
#                 'structure_dirs': self.structure_dirs
#             }
#             db_pdb_dicts.append(pdb_dict)
# 
#         # TODO multiprocessing is causing problems with tests. Maybe refactor to use mpi4py instead?
#         # Use multiprocessor pool to retrieve various data for each PDB
#         # pool = Pool()
#         results = map(extract_pdb_data, db_pdb_dicts)
# 
#         for pdb_results in results:
#             pdb_row_id = pdb_results['pdb_row_id']
#             pdb_row = models.PDBEntry.query.filter_by(id=pdb_row_id).first()
# 
#             if 'exception_message' in pdb_results and pdb_results.get('exception_message') == 'SIFTS file could not be downloaded':
#                 db.session.delete(pdb_row)
#                 continue
# 
#             for chain_row_id in pdb_results['chain_dicts']:
#                 chain_row = models.PDBChain.query.filter_by(id=chain_row_id).first()
#                 chain_dict = pdb_results['chain_dicts'][chain_row_id]
#                 for key in chain_dict:
#                     if key in ['chain_id', 'exception_message']:
#                         continue
#                     setattr(chain_row, key, chain_dict[key])
# 
#                 # Delete chain entries with exception message of 'DELETE_ME'.
#                 # These are cases where the sifts_uniprotAC does not match the
#                 # uniprotAC in DB_root (derived from the UniProt entry by
#                 # gather-uniprot.py), or where more than 90% of the
#                 # experimental sequence is unobserved
#                 if chain_dict['exception_message'] == 'DELETE_ME':
#                     db.session.delete(chain_row)
# 
#             # If all chain entries have been deleted, delete the entire PDB row.
#             if pdb_row.chains.count() == 0:
#                 db.session.delete(pdb_row)
# 
#         current_crawl_datestamp_row = models.DateStamps.query.filter_by(crawl_number=current_crawl_number).first()
#         current_crawl_datestamp_row.pdb_datestamp = now
#         if self.commit_to_db:
#             db.session.commit()
#         print 'Done.'


# Path: scripts/DoraGatherPDB.py
import argparse
from targetexplorer.pdb import GatherPDB



argparser = argparse.ArgumentParser(description='Gather cBioPortal data')
argparser.add_argument(
    '--nocommit',
    help='Run script, but do not commit to database.',
    action='store_true',
    default=False

)