"""
     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
from Pycard.twistedsupport import twistedModel
from twisted.internet import reactor
import Image, ImageOps, numpy
import wx, os, platform
import imageadj
from skylive.utils import genutils as utils
from skylive.lang import language
from skylive.fits import fitsimage, levels


class FitsOpener(model.Background,):

   def on_initialize(self, event):
      try:
         self._parent = self.getParent()
         self.userhome = self._parent.usrDefSavePath
         self.lang = self._parent.lang
      except:
         self.lang = 'en'
         self.userhome = os.path.expanduser("~")
      self.gui = 'imager'
      self.ItemText = language.getItemText

   def on_open_command(self, event):
      try:
         if self._parent.lastPath and os.path.exists(self._parent.lastPath):
            lpath = self._parent.lastPath
         else:
            lpath = self.userhome
      except:
         lpath = self.userhome
      selectFits = dialog.fileDialog(self, "Select Image:", lpath, ' ', 'FITS Image: (*.fit)|*.fit')
      if selectFits.accepted:
         self.fitsFile = selectFits.paths[0]
         try:
            self._parent.lastPath = os.path.split(self.fitsFile)[0]
         except:
            pass
         self.loadFits(self.fitsFile)

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

   def on_adjust_command(self, event=False):
      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")
      try:
         self.adjustImg._parent = self
      except:
         pass
      self.adjustImg.visible = True
      try:
         self.adjustImg._parent.origImage = [self.pilImage, self.xsizeBit, self.ysizeBit, self.min, self.max, self.med, self.img2, self.ToResize ]
      except:
         pass


   def loadFits(self, fitsFile):
      
      fitsfile = fitsimage.FitsImage(fitsFile, False)
      scidata = fitsfile.image
      self.autoMax = fitsfile.autoMaxLevel
      self.autoMin = fitsfile.autoMinLevel
      self.ToResize = fitsfile.pilResized
      self.min = fitsfile.min
      self.max = fitsfile.max
      self.med = fitsfile.med
      self.pilImage = fitsfile.pilOrI
      self.img = fitsfile.pilImage
      self.img2 = fitsfile.pilRaw
      self.xsizeBit = fitsfile.xsizeBit
      self.ysizeBit = fitsfile.ysizeBit
      image = wx.EmptyImage(fitsfile.xsizeBit, fitsfile.ysizeBit)
      image.SetData(fitsfile.pilImage.convert("RGB").tostring())
      self.imageBitmap = graphic.Bitmap()
      self.imageBitmap.setImageBits(image)
      self.components.ImageShow.bitmap = self.imageBitmap
      self.size = (fitsfile.xsizeBit+20, fitsfile.ysizeBit+100)
      try:
         self.MenuBar.setEnabled('menuPhoto', True)
      except:
         self.menuBar.setEnabled('menuPhoto', True)
      if fitsfile.pilResized:
         self.title = "Vista al  "+str(fitsfile.percresize)+"% delle dimensioni originali"

   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)
   
   def on_saveas_command(self, event):
      self.getAndSaveImage()
  
   def getText(self, item):
      return self.ItemText(self.lang, self.gui, item)

   def on_size(self, event):
      self.panel.SetSize(self.size)

def run():
   #app = model.Application(FitsOpener, './gui/fitsopener.rsrc.py')
   app = twistedModel.TwistedModelApplication(FitsOpener, './gui/fitsopener.rsrc.py')
   app.MainLoop()
