import numpy as np

from abbrator import Abbrator

import pdb

class Letterman(object):
    
    def __init__(self, ideogram, karyotype):
        """
            self.karyotype
            Abbrator
        """
        self.ideogram= ideogram
        self.karyotype= karyotype 
        self.init_params()


    def define_params(self):
        """
        @char_step_size: length/step unit of a character on the circos circle
        @threshold: abundance threshold which determines the color of the pathway name.
        @coors_between_letters: space between letters. check the unit of this: TODO!!!
        @total_coordinate_len: total number of coordinates on circle
        @coor_step_size: number of units that one coordinate covers
        """
        pass


    def calculate_font_color_abundance_threshold(self):
        total_abundance_value= self.ideogram.get_total_value()

        ### TODO: check the calculation of quartiles
        values= sorted([chrom.get_unique_total_value() for chrom in self.ideogram.chromosomes])
        
        ## yellow to red abundance threshold
        ## white-yellow colored pathways are more visible with darker letters
        ## red-dark red colored pathways are more visible with white ltters
        self.threshold1= np.percentile(values, 60)
        self.threshold2= np.percentile(values, 90)
       

    def init_params(self):
        """
            ideogram-wise parameters.
        
        """


        self.coor_step_size= 5
        
        
        self.calculate_font_color_abundance_threshold()
    
        # total number of features/coordinates at hand
        total_coordinate_len= len(self.ideogram)

        # total space for writing all pathway names
        total_ideogram_step_size= total_coordinate_len * self.coor_step_size

        ### broadest level will fit more letters.
        
        #### calculate this by dividing the total space by char_size/len  TODO 
        #### define the length of a character by finding how man units the set font
        #    corresponds to.
        
        
        #### TODO this will be changed. instead of setting total letters before hadn
        # we will set the the char_len before hand since we can have and idea of it
        # through the font size.
        
        if len(self.ideogram) < 500:
            n_total_letters= 135

        elif len(self.ideogram) > 500 and len(self.ideogram) < 2000:
            n_total_letters= 180

        elif len(self.ideogram) > 2000:
            n_total_letters= 250

        
        self.char_step_size= int(total_ideogram_step_size / n_total_letters)



    def yield_text(self, chrom):
        """
            chromosome-wise parameters
        """


        name= chrom.name
        
        n_coordinates= len(chrom)
        #####
        total_chromosome_step_size = n_coordinates * self.coor_step_size
        #####
        
        n_allowed_chars = int(np.floor(total_chromosome_step_size / self.char_step_size)) 
        
        abbr_pathway= Abbrator(name, n_allowed_chars).abbr
        
        ###
        chromosome_karyotype_name= chrom.get_coordinates()[0].get_name_by_level(1).strip()
        ###
        
        ### store abbreviations for each pathway in a dict
        #self.abbreviations[name] = abbr_pathway

        #### set the font color
        pathway_abundance= chrom.get_unique_total_value()
        
        if pathway_abundance < self.threshold1 :
            color = "dgrey"

        elif pathway_abundance >= self.threshold1 and pathway_abundance < self.threshold2:
            color= "vdgrey"
        
        else:
            color= "white"

        options= "color=%s" %color
        ####


        ### align the pathway name center
        free_space= total_chromosome_step_size - (len(abbr_pathway) * self.char_step_size)
        free_coors= free_space / self.coor_step_size 
        
        ### free space is from both sides
        init_coor= free_coors  / 2 
        

        ### TODO: check why this can be below 0.
        if init_coor < 0: 
            pdb.set_trace()
            init_coor= 0
         
        ### we give the blank penalty because we dont wanna move three step sizes for the character
        #   after the space character but a max of one step size.
        chrom_blank_penalty= 0
                
        for i in range(len(abbr_pathway)):            

            coor_index= int(init_coor) + int(i * self.char_step_size / self.coor_step_size) -1
            

            
            #if "HD" in abbr_pathway:
            #    pdb.set_trace()


            
            
            #if "ENE" in abbr_pathway:
            #    pdb.set_trace()

            letter= abbr_pathway[i] 
            
            if letter != " ":
                ### we dont wanna write dot(.)s on circos plot.
                
                
                penalty= np.floor(chrom_blank_penalty * self.char_step_size / self.coor_step_size / 2) 
                coor_index -= int(penalty)
                
                if coor_index < 0: coor_index= 0
                
                coor= chrom.get_coordinates()[coor_index] 
                crs= coor.get_coordinate()
                startCoor= crs[0] 
                
                line = [self.karyotype[chromosome_karyotype_name], str(startCoor), 
                        str(startCoor + int(self.char_step_size)), letter, options]

                yield "\t".join(line)+'\n'
            
            else:
                chrom_blank_penalty+=1



    def trash_note(self):
        #avg= float(total_value) / len(self)
        ### avg does not work in our case. check what are the light
        ### colors and what are the dark colors in the circos coloring
        ### scheme. in worst case, color dark if the abundance level s
        ### lower than 2/3 instead of averadge. 

    

        ### below parameters are related to the karyotype size!!
        ### TODO adjust them accordingly!!!!

            ### factors: directionality, color
            ### 
            #" current problems: 
            #    1 highlights and text coordinates do not match with the heatmap coordinates. check it out
            #    2 spaces between words should not take 3 times the siz of an empty character.
            #    3 ....



        #lenCharCoors= totalLetters / float(total_coordinate_len)   
        #lenCharCoors= 2
         
            #totalLetters= 300
            #lenCharCoors= 3

            #totalLetters= 200
            #lenCharCoors= 3
        
        
            #allowedCharLen = int(coordinateLen * lenCharCoors)
            
            
            
            
            ## below options did not work
            
            #option2= "label_rotate=no" 
            #option3= "label_parallel=no"
            #options= ",".join([option1, option2, option3])

            
            #free_char_cpace= allowed_char_len - len(abbr_pathway.replace(' ','').replace('.',''))
            
            #freeCharCoors= free_space * lenCharCoors * 5 

            #textCoors= int(len(abbr_pathway.replace(' ','')) * lenCharCoors) 


                #except:

                #    pdb.set_trace()
                

                    #penalty = (blank_penalty * int((lenCharCoors+1)*5)) - int(blank_penalty* lenCharCoors*5)


        pass
