from Pycard import model, graphic, dialog
import wx, os
#from cStringIO import StringIO


class LiveDuplicate(model.Background):

   def on_initialize(self, event):
      self.SetSizeHints(80, 87)

   def resizeImage(self, image):
      nolog = wx.LogNull()
      newBitmap = graphic.Bitmap()
      if hasattr(image, 'getBits'):
         # on OSX we have a Pycard.image.Bitmap instance!
         wximage = wx.ImageFromBitmap(image.getBits())
      else:
         wximage = wx.ImageFromBitmap(image)
      w, h = wximage.GetSize()
      ww, wh = self.size
      ih = (int(ww-1)*int(h))/int(w)
      if ih > int(wh-40):
         iw = (int(wh-40)*int(w))/int(h)
         ih = (iw*int(h))/int(w)
      else:
         iw = (int(w)*ih)/int(h)
      wximage.Rescale(iw, ih)
      newBitmap.setImageBits(wximage)
      self.LiveBitmap = newBitmap

      self.title="Live Image telescope %s" % str(self._parent.telescopesel)
      self.components.Image1.autoRefresh = 0
      self.components.Image1.size = (iw, ih)
      self.components.Image1.clear()
      self.components.Image1.autoRefresh = 1
      self.components.Image1.drawBitmapScaled(newBitmap, (0, 0), (iw, ih))
      self.panel.SetSize(self.size)
      #if self.ignoreSizeEvent == 1:
      #self.SetClientSize((iw, ih))
      del nolog

   def setLiveImage(self, image):
      nolog = wx.LogNull()
      self.title="Live Image telescope %s" % str(self._parent.telescopesel)
      self.originalimage = image
      self.resizeImage(image)
      del nolog

   def on_menuSave_select(self, event):
      self.userhome = self._parent.usrDefSavePath
      result = dialog.saveFileDialog(self, 'Save BMP', self.userhome, 'snap.bmp', 'BMP Files: (*.bmp)|*.bmp')
      path = self.userhome
      if result.accepted:
         path=result.paths[0]
         if os.path.exists(path):
            try:
               os.unlink(path)
               self.LiveBitmap.saveFile(path)
            except:
               dialog.alertDialog("ERROR: Cannot overwrite "+str(path))
         else:
            self.LiveBitmap.saveFile(path)
      self.mainPathChange(path)


   def mainPathChange(self, path):
      self.userhome = self._parent.usrDefSavePath
      newpath = path
      if not os.path.isdir(path):
         newpath, file = os.path.split(path)
      if newpath != self.userhome and os.path.isdir(newpath):
         self._parent.components.PathField.text = newpath
         self._parent.config.put_usrDefaultPath(newpath)
         self._parent.usrDefSavePath = newpath


   def on_size(self, event):
      self.resizeImage(self.originalimage)

   def on_close(self, event):
      self._parent.livedup = False
      event.skip()
