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