__doc__="Class ProgressBarTW for displaying progress of some operation. TW means using TopWindow class. P.S. Sorry for my bad english :)"
__name__="ProgressBarTW class"

def ru(s):return s.decode('utf-8')

class ProgressBarTW:
  __module__ = __name__

  def __init__(self,type=1,watch_focus=True):
    import e32,topwindow,graphics
    from sysinfo import display_pixels
    from appuifw import app,note
    self.app = app
    self.note = note
    self.new_image = graphics.Image.new
    self.sleep = e32.ao_sleep
    self.old_focus = self.app.focus
    self.watch_focus = watch_focus
    self.type = type
    self.t = 1
    (self.screen_width,self.screen_height) = display_pixels()
    self.current_value = 0
    self.pb_window = topwindow.TopWindow()
    self.set_fonts()
    if type == 2:
      self.set_fonts(text_font=u'LatinBold19',text_color=0x0)
    self.k =0.1
    self.pb_window.size = (self.screen_width/2,self.screen_height*self.k)
    self.pb_window.position = (self.screen_width/2-self.pb_window.size[0]/2,self.screen_height/2-self.pb_window.size[1]/2)
    self.set_window_attr()
    self.set_colors()
    if self.type == 1:
      self.pb_image = graphics.Image.new((1,1))
      self.pb_window.add_image(self.pb_image, (0,0))

  def set_window_attr(self,back_color=0xBEBEBE,corner_type = 'square',shadow = 1):
    self.pb_window.background_color = back_color
    self.pb_window.shadow = shadow
    self.pb_window.corner_type = corner_type

  def set_window_position(self,new_position):
    try:
      self.pb_window.position = new_position
    except:
      self.pb_window.position = (self.screen_width/2-self.pb_window.size[0]/2,self.screen_height/2-self.pb_window.size[1]/2)

  def set_window_size(self,new_size):
    try:
      self.pb_window.size = new_size
      self.pb_window.remove_image(self.pb_image)
      self.pb_image = self.pb_image.resize(map(lambda(x):x-2,new_size))
      self.pb_window.add_image(self.pb_image,(1,1))
      self.set_window_position((self.screen_width/2-new_size[0]/2,self.screen_height/2-new_size[1]/2))
    except:
      self.pb_window.size = (self.screen_width/2,self.screen_height*self.k)

  def set_colors(self,bar_color=0x0000ff,rect_color=0x0,back_color = 0xBEBEBE):
    self.bar_color = bar_color
    self.rect_color = rect_color
    self.back_color = back_color

  def set_fonts(self, text_font = 'dense',text_color=0x0, percent_font = 'dense',percent_color=0xef0000):
    self.text_font = text_font
    self.text_color = text_color
    self.percent_font = percent_font
    self.percent_color = percent_color

  def check_focus(self,fg):
    if self.current_value >= self.total:
      return
    if fg:
      self.pb_window.show()
      self.foreground = True
    else:
      self.pb_window.hide()
      self.foreground = False

  def begin_progress(self, total=100, text=ru("Подождите пожалуйста")):
    self.total = total
    self.note_text = unicode(text)
    self.current_value = 0
    self.foreground = True
    if self.watch_focus:
      self.old_focus = self.app.focus
      self.app.focus = self.check_focus
    if self.type == 2:
      self.begin_note()

  def end_progress(self):
    if self.type == 1:
      self.do_progress(self.total)
    self.app.focus = self.old_focus
    self.sleep(.5)
    self.pb_window.hide()

  def hide(self):
    self.pb_window.hide()

  def show(self):
    self.pb_window.show()

  def inc(self, value = 1, text = u""):
    if len(text) != 0:
      self.note_text = text
    self.do_progress(self.current_value + value)

  def get_text_size(self,text,font,maxwidth=-1):
    im = self.new_image((100,100))
    (textrect,temp,num_chars)=im.measure_text(text, font=font, maxwidth=maxwidth)
    im = None
    return (textrect[2]-textrect[0],textrect[3]-textrect[1])

  def wrapped_text(self, back_size, text_str):
    im_size = tuple(map(lambda(x):x-10,back_size))
    im = self.new_image(im_size)
    im.clear(self.back_color)
    temp_str = text_str
    lines = []
    font_height = 0
    wrapped = False
    while not wrapped:
      (textrect,temp,num_chars)=im.measure_text(temp_str, font=self.text_font,maxwidth=im_size[0])
      if font_height == 0:
        font_height = max(font_height,(textrect[3]-textrect[1]))
      if len(temp_str) > num_chars:
        lines.append(temp_str[:num_chars])
        temp_str = temp_str[num_chars:]
      else:
        lines.append(temp_str)
        wrapped = True
    lines_count = len(lines)
    text_height = lines_count*font_height + (font_height-1)
    if text_height > im_size[1]:
      if lines_count > 1:
        lines.pop()
        lines_count -= 1
      lines[-1] = lines[-1][:len(lines[-1])-3]+u"..."
    text_y = font_height
    for i in range(lines_count):
      im.text((0,text_y),lines[i],fill=self.text_color,font=self.text_font)
      text_y += 1 + font_height
    return im

  def draw_note(self):
    try:
      self.pb_window.remove_image(self.pb_image)
    except: pass
    self.pb_window.corner_type = 'corner1'
    self.pb_image = self.wrapped_text(self.pb_window.size,self.note_text)
    self.pb_window.add_image(self.pb_image,(5,5))

  def draw_bar(self):
    (text_w,text_h) = self.get_text_size(self.note_text,self.text_font,maxwidth=self.pb_image.size[0])

    cur_x = (self.pb_image.size[0]-1)*self.cur_percent/100
# основной прямоугольник "подложка"
    self.pb_image.rectangle((0,0,self.pb_image.size[0],self.pb_image.size[1]),fill = self.back_color,outline = self.rect_color)
# прямоугольник прогресса
    self.pb_image.rectangle((1,text_h+2,cur_x,self.pb_image.size[1]-1),fill = self.bar_color,outline = self.bar_color)

# отделяем полоску прогресса от текста заголовка
    self.pb_image.line((1,text_h+2,self.pb_image.size[0]-1,text_h+2),fill = self.rect_color,outline = self.rect_color)

# добавляем текст процента на полоску прогресса
    percent_text = u"%d %%"%self.cur_percent
    per_text_size = self.get_text_size(percent_text,'dense')
    per_text_x = self.pb_image.size[0]/2 - per_text_size[0]/2
    per_text_y = (text_h+self.pb_image.size[1]+3)/2+per_text_size[1]/2
    self.pb_image.text((per_text_x,per_text_y),percent_text,fill = self.percent_color,font = self.percent_font)
# и добавляем заголовок окна над полоской прогресса
    text_x = self.pb_image.size[0]/2 - text_w/2
    text_y = text_h
    self.pb_image.text((text_x,text_y),self.note_text,fill = self.text_color,font = self.text_font)
    self.pb_window.add_image(self.pb_image,(1,1))

  def begin_note(self):
    i =0.01
    self.pb_window.shadow = 0
    self.pb_window.background_color = 0xc0c0c0
    self.pb_window.corner_type = 'corner1'
    while i <= 0.4:
      self.pb_window.hide()
      new_size = (self.screen_width,self.screen_height*i)
      self.set_window_size(new_size)
      new_position = (0,self.screen_height -self.pb_window.size[1])
      self.set_window_position(new_position)
      self.pb_window.show()
      self.sleep(.01)
      i += 0.01
      if new_size[1] > 20:
#        pass
        self.draw_note()

  def do_progress(self, current_value):
    if not self.foreground:
      return
    if (self.pb_window.visible == 0)      and(self.foreground):
      self.pb_window.show()
#    self.pb_window.hide()
    if len(self.pb_window.images) != 0:
      self.pb_window.remove_image(self.pb_image)
    self.current_value = current_value
    if self.current_value > self.total:
      self.current_value = 1
    self.cur_percent = 100*current_value/self.total
    if self.cur_percent < 0:
      self.cur_percent = 0
    elif self.cur_percent > 100:
      self.cur_percent = 100
    if self.type == 1:
      self.draw_bar()
    else:
      self.draw_note()
    self.sleep(.01)
