#!/usr/bin/env python
#-*- coding: UTF-8 -*-

import urllib2
import shutil
import zipfile
import wx
from   stomamisc import *

class InstallDialog(wx.Dialog):
    ID_START = wx.NewId()
        
    def __init__(self, parent, config, writeToLogwin, url):
        """  """
        wx.Dialog.__init__(self, parent, -1, TITLE + ' - install new release', style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self.writeToLogwin = writeToLogwin
        self.url = url

        sizer = wx.BoxSizer(wx.VERTICAL)
        row1 = wx.BoxSizer(wx.VERTICAL)
        self.tc = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_DONTWRAP)      
        self.tc.Enable(False)
        background_color = wx.SystemSettings_GetColour(READONLY_COLOR)
        self.tc.SetBackgroundColour(background_color)
        row1.Add(self.tc, 2, wx.EXPAND | wx.ALL, GAP)        

        self.butstart = wx.Button(self, self.ID_START, '&Start installation')
        butclose = wx.Button(self, wx.ID_CLOSE)
        self.Bind(wx.EVT_BUTTON, self.onButtonStart, id = self.ID_START)
        self.Bind(wx.EVT_BUTTON, self.onButtonClose, id = wx.ID_CLOSE)     
        row3 = wx.BoxSizer(wx.HORIZONTAL)
        row3.Add(self.butstart, 1, wx.GROW | wx.RIGHT, GAP)
        row3.Add(butclose, 1, wx.GROW | wx.LEFT, GAP)

        sizer.Add(row1, 3, wx.GROW | LRT, BORDER)
        
        sl = wx.StaticLine(self, -1)
        sizer.Add(sl, 0, wx.GROW | LRT, BORDER)
        sizer.Add(row3, 0, wx.GROW | wx.ALL, BORDER + GAP)
        self.SetSizer(sizer)
        self.SetMinSize(wx.Size(400, 360))
        self.Fit()
        self.Centre()
        self.logText('the new release to be installed is %s' % url[-17:])
        self.logText("press 'Start installation'")
    #-------------------------------------------------------------------------------------------

    def logText(self, text, color = None):
        if color != None:
            start = self.tc.GetInsertionPoint()
        self.tc.WriteText('- %s\n' % text)
        self.writeToLogwin('Installer - %s' % text)
        if color != None:
            stop = self.tc.GetLastPosition()
            self.tc.SetStyle(start, stop, wx.TextAttr(color))
        self.tc.ShowPosition(-1)
        wx.SafeYield(self)
    #-------------------------------------------------------------------------------------------

    def backupCurrentFiles(self, bkupdir):
        dirlist = os.listdir(APPPATH)
        for name in dirlist:
            spname = os.path.join(APPPATH, name)
            tpname = os.path.join(bkupdir, name)
            if os.path.isfile(spname):
                if os.path.islink(spname):
                    continue                                                
                shutil.copy(spname, tpname)
    #-------------------------------------------------------------------------------------------

    def installNewFiles(self, zipfname):
        zfile = zipfile.ZipFile(zipfname, 'r')
        names = zfile.namelist()
        for name in names:
            if name.endswith('/') or name == 'READ.ME': continue
            outfname = os.path.join(APPPATH, name[9:])
            cf = zfile.read(name)
            self.logText(outfname)
            outfile = open(outfname, 'wb')
            outfile.write(cf)
            outfile.close()
    #-------------------------------------------------------------------------------------------
         
    def onButtonStart(self, event):
        self.butstart.Enable(False)
        try:
            self.logText('making backup of current installation ...')
            bkupdir = os.path.join(APPPATH, 'backup')
            if not os.path.exists(bkupdir):
                os.mkdir(bkupdir, 0777)
            if not os.path.exists(bkupdir):
                raise
            self.logText('copying files ...') 
            self.backupCurrentFiles(bkupdir)
            self.logText('backup completed')
        except:
            self.logText('could not backup current installation - giving up', RED)
            return        
        try:
            self.logText('trying to connect to download site ...')            
            mysock = urllib2.urlopen(self.url, timeout = 5)
        except:
            self.logText('could not connect to download site - giving up', RED)
            return
        try:
            self.logText('starting download - this can take a while ...') 
            file2save = mysock.read()
            self.logText('download finished')
        except:
            self.logText('could not download file - giving up', RED)
            return       
        localfname = os.path.join(APPPATH, self.url[-17:])
        try:   
            self.logText('trying to store downloaded file locally ...')
            localfile = open(localfname, 'wb')
            localfile.write(file2save)
            localfile.close()
            self.logText("file '%s' stored locally" % localfname)
        except:
            self.logText('could not store file - giving up', RED)
            return
        self.logText('installing new files ...')
        try:
            self.installNewFiles(localfname)
            self.logText('new release successfully installed')
        except:            
            self.logText('could not install files - giving up', RED)
            return
        self.tc.WriteText('\n')
        self.logText('shutdown and restart %s to finish the installation' % TITLE)
    #-------------------------------------------------------------------------------------------

    def onButtonClose(self, event):
        self.Destroy()

# - class InstallDialog(wx.Dialog):--------------------------------------------------------------
 