"""
     Copyright (C) 2007-2009 Franco Lanza <nextime@nexlab.it>
     Copyright (C) 2007-2009 Sandro Aliano <ita595@hotmail.com>
     Copyright (C) 2007-2009 Ivan Bellia <skylive@skylive.it>

     Web site: http://www.astronomix.org/trac/Skylive-NG

     This file is part of Skylive-NG.

     Skylive-NG is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.

     Skylive-NG is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with Skylive-NG.  If not, see <http://www.gnu.org/licenses/>.
"""

from Pycard import model, dialog, graphic
import os, wx, platform
import gui, imageadj, info
from zipfile import ZipFile as zip
from skylive.lang import language

class SkyliveImager(model.Background):

   def on_initialize(self, event):
      try:
         self.parent = self.getParent()
         self.autoMax = self.parent.autoMax
         self.autoMin = self.parent.autoMin
         self.userhome = self.parent.usrDefSavePath
         self.header = self.parent.fitsHeader
      except:
         pass
      #this don't work with wxPython 2.6
      self.lang = self.parent.lang
      self.gui = 'imager'
      self.ItemText = language.getItemText
      self.setGui()
      try:
         self.defineFrom()
      except:
         pass


   def refresh(self):
      if self.origImage[7]:
         imgTomod = self.origImage[0].resize((self.origImage[1], self.origImage[2]))
      else:
         imgTomod = self.origImage[0]
      image = wx.EmptyImage(self.origImage[1], self.origImage[2])
      image.SetData(imgTomod.convert("RGB").tostring())
      newBitmap = graphic.Bitmap()
      newBitmap.setImageBits(image)
      self.components.ImageShow.bitmap = newBitmap
      print "FATTO"

   def on_exit_command(self, event):
      self.close()


   def on_ButtonClose_mouseClick(self, event):
      self.close()

   def on_ButtonDownload_mouseClick(self, event):
      try:
         #self._parent.callInTwisted('downloadFits', self.telescope)
         self._parent.TwistedLoop.downloadFits(self.telescope)
      except:
         pass
      self.close()

   def on_ButtonSave_mouseClick(self, event):
      # XXX: impostare meglio estensione e filename
      # XXX: gestire anche la conversione in bmp/jpg/altro
      # XXX: gestire anche il saveimage per lo snapshot
      if self.actionSave =="fit":
         defaultFN = self._parent.components.FileName.text+".fit"
         result = dialog.saveFileDialog(self, self.getText('SaveDialog_FIT'), self.userhome, defaultFN, 'FITS Files: (*.fit)|*.fit')
         if result.accepted:
            path = result.paths[0]
            if os.path.exists(path):
               try:
                  os.unlink(path)
                  readFile = zip(self.fitfile, 'r')
                  fitsData = readFile.read("SkyFrame.fit")
                  readFile.close()
                  savedFile = open(path, 'wb')
                  savedFile.write(fitsData)
                  savedFile.close()
               except:
                  dialog.alertDialog("ERROR: Cannot overwrite "+str(path))
            else:
               readFile = zip(self.fitfile, 'r')
               fitsData = readFile.read("SkyFrame.fit")
               readFile.close()
               savedFile = open(path, 'wb')
               savedFile.write(fitsData)
               savedFile.close()
      elif self.actionSave == "bmp":
         result = dialog.saveFileDialog(self, self.getText('SaveDialog_BMP'), self.userhome, 'snap.bmp', 'BMP Files: (*.bmp)|*.bmp')
         if result.accepted:
            path=result.paths[0]
            if os.path.exists(path):
               try:
                  os.unlink(path)
                  self.SnapBitmap.saveFile(path)
               except:
                  dialog.alertDialog("ERROR: Cannot overwrite "+str(path))
            else:
               self.SnapBitmap.saveFile(path)
      else:
         pass
      self.mainPathChange(path)
      
               
   def on_adjust_command(self, event=None):
      if platform.system == "Microsoft":
         sysType = "Windows"
      else:
         sysType = platform.system()
      if not os.path.exists(os.path.normpath("./gui/imageadj."+sysType+".rsrc.py")):
         sysType = "Linux"
      self.adjustImg = model.childWindow(self, imageadj.imageAdj, "./gui/imageadj."+sysType+".rsrc.py")
      self.adjustImg._parent = self
      self.adjustImg.visible = True

   def defineFrom(self):
      if self.fromEvent == "photodown":
         self.components.ButtonSave.label = self.getText('ButtonSave_FIT')
         self.actionSave = "fit"
         try:
            self.MenuBar.setEnabled('menuPhoto', True)
            self.MenuBar.setEnabled('menuInfo', True)
         except:
            self.menuBar.setEnabled('menuPhoto', True)
            self.menuBar.setEnabled('menuInfo', True)
      elif self.fromEvent == "snapshot":
         self.components.ButtonSave.label = self.getText('ButtonSave_BMP')
         self.actionSave = "bmp"
      else:
         pass

   def on_readHeader_command(self, event):
      hd = self.header
      rsrc = "./gui/info.rsrc.py"
      try:
         if self.parent.systemType == 'Darwin':
       	    rsrc = "./gui/info.rsrc.Darwin.py"
      except:
         pass
      self.headerPop = model.childWindow(self, info.infoBox, rsrc)
      self.headerPop.title = "Fits Header"
      self.headerPop.components.infobox.text='FIELD\t\t\tVALUE\n'
      fields = self.header.keys()
      for x in fields:
         try:
            txtHeader = str(hd[x])+'\n'
            self.headerPop.components.infobox.appendText(txtHeader)
         except:
            pass

   def on_ButtonCompare_mouseClick(self, event):
      try:
         #self._parent.callInTwisted('downloadDss', self.imageData[0], self.imageData[1],
         self._parent.TwistedLoop.downloadDss(self.imageData[0], self.imageData[1],
               self.imageData[2], self.imageData[3])
      except:
         pass
   
   def getText(self, item):
      return self.ItemText(self.lang, self.gui, item)
   
   def setGui(self):
      self.components.ButtonDownload.label = self.getText('ButtonDownload')
      self.components.ButtonCompare.label = self.getText('ButtonCompare')
      self.components.ButtonClose.label = self.getText('ButtonClose')
      self.components.ButtonSaveAs.label = self.getText('ButtonSaveAs')
      submenu = ['menuFileExit', 'menuAdjustPhoto', 'menuInfoPhoto']
      try:
         for item in submenu:
            idmenuItem = self.menuBar.getMenuId(item)
            self.MenuBar.SetLabel(idmenuItem, self.getText(item))
      except:
         pass
   
   def on_ButtonSaveAs_mouseClick(self, event):
      self.getAndSaveImage()
   
   def getAndSaveImage(self):
      try:
         imageFromPil = self.pilImage
      except:
         imageFromPil = False
      if imageFromPil:
         aStyle = wx.SAVE | wx.HIDE_READONLY | wx.OVERWRITE_PROMPT
         result = dialog.saveFileDialog(self, self.getText('SaveDialog_SaveAs'), self.userhome, self._parent.components.FileName.text, 'BMP File: (*.bmp)|*.bmp|JPG File: (*.jpg)|*.jpg', aStyle)
         if result.accepted:
            path=result.paths[0]
            if not os.path.splitext(os.path.split(path)[1])[1]:
               dialog.alertDialog(self, self.getText('SaveDialog_alertSaveAs'))
               self.getAndSaveImage()
            else:
               imageFromPil.save(path)
         self.mainPathChange(path)

   def mainPathChange(self, path):
      newpath = path
      if not os.path.isdir(path):
         newpath, file = os.path.split(path)

      if newpath != self.userhome and os.path.isdir(newpath):
         print 'diverso cambio'
         self.parent.components.PathField.text = newpath
         self.parent.config.put_usrDefaultPath(newpath)
         self.parent.usrDefSavePath = newpath
            
            
            
            
            
            
