#!/usr/bin/python3

# orthologer - Pipeline for deducing orthology from fasta files.
# Copyright (C) 2005-2023 E. Zdobnov lab: F. Tegenfeldt
# <fredrik.tegenfeldt@unige.ch> based on code by E. Kriventseva
#
# This file is part of orthologer.
#
# orthologer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orthologer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with orthologer.  If not, see <http://www.gnu.org/licenses/>.
'''
Extract fasta entries with given species keys.
Pipeline usage: SELECT (cdhit)
'''
from __future__ import print_function

#
# This code checks for a given fasta file if the sequences are proteins or nucletides.
#
import sys
import argparse
import fasta_tools as FT
import orthologer_tools as OT

def readKeys( fh ):
    labelsref=[]
    for rawline in fh.readlines():
        line = rawline.strip().rstrip('\n')
        if len(line)==0: continue
        if line[0]=='#': continue
        labelsref.append(line)

    return labelsref
        
def process( flabelsref, fastaseq ):
    # get fasta ref
    labelsref = readKeys( flabelsref )

    # get data fasta requiring labelsref
    (ec,stypeseq,fastaseqDB,specseqDB)=FT.readFastaVect(fastaseq,None,labelsref)
    if ec>0:
        OT.print_error(('failed reading fasta seq file with error code %d')%(ec))
        return 255

    # print all sequences
###    for lbl,seq in fastaseqDB.items():
    for fseq in fastaseqDB:
        print(('>%s')%(fseq[0]))
        print(('%s')%(fseq[1]))

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Get sequences from blastclust result')

    parser.add_argument('-k', '--keys', dest='keys', help='keys to be used', metavar='FILE', required=True)

    parser.add_argument('-d', '--fastaseq', dest='fastaseq', help='fasta file from where the sequences are retrieved', metavar='FILE', required=True)


    options = parser.parse_args()

    # open fastaref file
    try:
        fkeys = open(options.keys)
    except IOError:
        OT.print_error('failed to open fasta ref file %s' % (options.keys))
        sys.exit(255)

    # open fastaseq file
    try:
        fastaseq = open(options.fastaseq)
    except IOError:
        OT.print_error('failed to open fasta seq file %s' % (options.fastaseq))
        sys.exit(255)

    # process file
    process( fkeys, fastaseq )

    fkeys.close()
    fastaseq.close()
