#!/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/>.

'''
Uses blastclust in order to identify closely related genes within one fasta file.
Pipeline usage: SELECT (blastclust)
'''
from __future__ import print_function

import sys
import argparse
import fasta_tools as FT
import orthologer_tools as OT

def process( blastclust, fasta, representative, clsize ):
    # get all labels
    labels=FT.readBlastclust(blastclust, representative, clsize )

    # get fasta
    (errorcode,stype,fastaDB,speciesDB)=FT.readFastaVect(fasta,None,labels)

    if errorcode>0:
        OT.print_error(('failed reading fasta file with error code %d')%(errorcode))
        return 255

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

if __name__ == '__main__':

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

    parser.add_argument('-f', '--fasta', dest='fasta', help='fasta file', metavar='FILE', required=True)
    parser.add_argument('-b', '--blastclust', dest='blastclust', help='blastclust output', metavar='FILE', required=True )
    parser.add_argument('-R', '--representative',  dest='representative', help='get fasta for the representative sequences only', action='store_true', default=False )
    parser.add_argument('-S', '--size', dest='clsize', help='min cluster size', metavar='int', default=2, type=int )

    options = parser.parse_args()

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

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

    # process file
    process( blastclust, fasta, options.representative, options.clsize )
