# -*- 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 clustal_phyml(DataConverter):
    
    def __init__(self, path):
        super( clustal_phyml , self ).__init__( path )
        self.program_name = 'Clustal2Phylip-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 != 'clustal':
            raise UnSupportedFormatError("support only clustal 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, 'clustal')
            except Exception, err:
                f_log.error( "failed to read clustal alignment", exc_info= True)
                raise UnSupportedFormatError( "the conversion from clustal 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 clustal to phylip-relaxed failed")    
        return outFileName 
    
    def convertedFormat(self):
        return [('CLUSTAL', 'PHYLIP-RELAXED')]