#from alignments.AncestralState import AncestralState
#from alignments.AncestralStatesList import AncestralStatesList
import os.path
import traceback

class PPParser(object):

    """
        Parses ancestral states text files that are generated by the MEGA/MEGA-CC
        software as a part of Maximum Parsimony tree construction
        
        On success, call get_ancestral_states to a list of AncestralState objects
        generated from the ancestral states text file
    """
    def __init__(self):
        self._input_file_name = ''
     #   self._ancestral_states = AncestralStatesList()
        self._messages = []
        
    @property
    def input_file_name(self):
        return self._input_file_name
    
    @input_file_name.setter
    def input_file_name(self, value):    
        self._input_file_name = value
        
    @property
    def messages(self):
        return self._messages
    
    def parse(self):
        try:
            print 'parsing pp file...'
            result = False
            if os.path.isfile(self._input_file_name) == False:
                IOError('ancestral states file not found')
            input_file = open(self._input_file_name, 'r')
            lines = input_file.readlines()
            input_file.close()
          #  self._set_filename(self._input_file_name)#lines[1])
          #  self._set_newick_string(lines[4])
           # index = 7
            #while index < len(lines):
             #   self._parse_line(lines[index])
              #  index += 1
           # result = (self._ancestral_states.num_nodes > 3) 
            self._parse_line(lines)		   
            if len(lines)>2:#result == True:
                pass#print 'successfully parsed ancestral states file: ' + str(self._ancestral_states.num_nodes) + ' taxa'
            else:
                print 'failed to parse ancestral states file'
            return result
        except Exception as e:
            traceback.print_exc()           
            self._messages.append(str(e))
            return False            
        
            
    def _parse_line(self, EP):
        print EP[0]
        #open('AAA','r').readlines()		
        self.CellID = EP[0].split('"')[1]	
        Head=EP[2].strip().split(',')
        Len=len(Head)	
        Col2Nuc={}
        c=1
        Len=c+4	
        while c<Len:
            Col2Nuc[c]=Head[c].split('/')[0]
            c+=1
       # print Col2Nuc
        EP=EP[3:]
        Seq=''
        c=0	
        self._pp_states=[]
        self.all_pp=[]		
        for i in EP:
           i=i.strip().split(',')
          # Nuc=OriSeq[c]#i[0]
           EPls=[]
           EP2Nuc={}
           for Col in Col2Nuc:
               Val=float(i[Col])
               EPls.append(Val)
               EP2Nuc[Val]=Col2Nuc[Col]
           EPls.sort()
           #Seq+=EP2Nuc[EPls[-1]]
           #if EP2Nuc[EPls[-1]]!=Nuc and Nuc!='?': print 'A'	,i 
           self._pp_states.append(EP2Nuc[EPls[-1]]+'\t'+str(EPls[-1]))		   
          # if Nuc=='?': Seq+=EP2Nuc[EPls[-1]]	
  	
    def get_cellName(self):
       return self.CellID  
	
    def get_all_pp(self):
        return self.all_pp	
        
    def get_pp_states(self):
        return self._pp_states
    