# -*- coding: utf-8 -*-
########################################################################################
#                                                                                      #
#   Author: Bertrand Néron                                                          #
#   Organization:'Biological Software and Databases' Group, Institut Pasteur, Paris.   #  
#   Distributed under GPLv2 Licence. Please refer to the COPYING.LIB document.         #
#                                                                                      #
########################################################################################

import os
from logging import getLogger
f_log = getLogger(__name__)

from Mobyle.MobyleError import MobyleError , UnSupportedFormatError
from Mobyle.Converter.DataConverter import DataConverter

from Bio import AlignIO

class stockholm_phyml(DataConverter):
    
    def __init__(self, path):
        super( stockholm_phyml , self ).__init__( path )
        self.program_name = 'Stockholm2Phylip-relaxed'

    def detect(self, dataFileName):
        #we lay on squizz to detect the format file
        return None, None
    
    def detectedFormat(self):
        #we lay on squizz to detect the format file
        return []
    
    def convert(self, dataFileName , outputFormat , inputFormat = None):
        outputFormat = outputFormat.lower()
        assert outputFormat == 'phylip-relaxed'
        
        if inputFormat is None:
            raise UnSupportedFormatError("the input format must be specify" )
        inputFormat = inputFormat.lower()
        
        if inputFormat != 'stockholm':
            raise UnSupportedFormatError("support only stockholm as input, provide " + str(inputFormat))
        with open(dataFileName) as data_input:
            #read allow only one multiple alignment
            #for more msa (after bootstarp) use parse
            #but for now squiz manage only one msa perfile
            try:    
                align = AlignIO.read(data_input, 'stockholm')
            except Exception, err:
                f_log.error( "failed to read stockholm alignment", exc_info= True)
                raise UnSupportedFormatError( "the conversion from stockholm to phylip-relaxed failed")
        outFileName = os.path.splitext( dataFileName )[0] + "." + outputFormat
        with  open(outFileName, 'w') as output:
            try:
                AlignIO.write(align, output , 'phylip-relaxed')
            except Exception, err:
                f_log.error( "failed to write phylip-relaxed alignment", exc_info= True)
                raise UnSupportedFormatError( "the convertion from stockholm to phylip-relaxed failed")    
        return outFileName 
    
    def convertedFormat(self):
        return [('STOCKHOLM', 'PHYLIP-RELAXED')]