########################################################################
#
#  Copyright (C) 2009, CZ.NIC, z.s.p.o.
# 
#  This file is part of dnstester.
#
#  dnstester 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.
#
#  dnstester 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
########################################################################

import sys
import pygtk
pygtk.require("2.0")
import gtk, gobject
import threading, thread

import lang
import devices
import net
from page import Page
import images
import config
import credentials
from errorbox import ErrorBox

class PageDevUpdateProgress(Page):
    
    title = 'devupdate_title'
    number = 2

    def __init__(self, parent):
        Page.__init__(self, parent)
        self.widget = self.create_vbox()


    def create_vbox(self):
        vbox = gtk.VBox()
        vbox.set_border_width(20)
        vbox.set_spacing(20)
        
        # add frame with label
        label = gtk.Label()
        lang.bind(label, 'downloading_devlist')
        self.device_update_status = label
        vbox.pack_start(label, False, False)

        self.vrtule = gtk.Image()
        self.vrtule.set_from_file(images.fullname('loader.gif'))
        self.vrtule.show()
        vbox.pack_start(self.vrtule, False, False)

        vbox.show_all()
        return vbox


    def on_before_show(self):
        self.start_device_update()


    def update_async(self):
        cred = credentials.update_credentials_async()
        result = devices.update_devices_async()
        self.parent.netinfo = net.NetworkInfo()
        gobject.idle_add(self.finish_device_update, (result, cred))


    def start_device_update(self):
        self.parent.enable_back_button(False)
        lang.bind(self.device_update_status, 'downloading_devlist')
        threading.Thread(target=self.update_async).start()


    def finish_device_update(self, result):
        (devresult, cred) = result
        if not devresult:
            print 'Internal error while updating device list.'
            sys.exit()

        if not cred:
            ErrorBox(self.parent, 'devupdate_no_credentials')
        else:
            config.id, config.key = cred

        if devices.current_version.split('.') > config.version.split('.'):
            ErrorBox(self.parent, 'newer_version')

        self.parent.reset_selectdevice()
        self.parent.set_page_complete(self.widget, True)
        self.parent.next()
        self.widget.hide()


