# -*- coding: utf-8 -*-

"""
Module implementing GuiRestore.
"""

from PyQt4.QtGui import QWidget
from PyQt4.QtCore import pyqtSignature

from Ui_guirestore import Ui_GuiRestore

from PyQt4 import QtGui
import logging
import sys
import cfg, wbfs2fat

logger = logging.getLogger(__name__)

class GuiRestore(QWidget, Ui_GuiRestore):
    """
    Class documentation goes here.
    """
    def __init__(self, parent = None):
        """
        Constructor
        """
        QWidget.__init__(self, parent)
        self.setupUi(self)
        cfg.options.restore = ""
        self.readcfg()

    def readcfg(self):
        self.dev_name.setText(cfg.dev.name)
        self.checkoptions()

    def checkoptions(self, fix=0):
        self.plainTextEdit.clear()
        state, check = cfg.dev.checkoptions(fix)
        for line in check:
            self.plainTextEdit.appendPlainText(line+"\n")
        if state & 1: self.readcfg()
        elif state & 2: self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ignore | QtGui.QDialogButtonBox.Cancel)
        elif state & 4: self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel)
        else: self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
        return state

    @pyqtSignature("")
    def on_backup_dialog_clicked(self):
        """
        Slot documentation goes here.
        """
        self.backup_name.setText(QtGui.QFileDialog.getOpenFileName(self, 'Select Backup',  cfg.options.backup_dir))

    @pyqtSignature("QString")
    def on_backup_name_textChanged(self, p0):
        """
        Slot documentation goes here.
        """
        cfg.options.restore = str(p0)
        self.checkoptions()

    @pyqtSignature("")
    def on_buttonBox_accepted(self):
        """
        Slot documentation goes here.
        """
        if self.checkoptions(1): return
        self.buttonBox.setEnabled(0)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Abort)
        try:
            cfg.dev.manual_restore()
            self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Close)
        except Exception:
            logger.error("Exception caught",exc_info=1)
            self.plainTextEdit.appendPlainText("ERROR: "+str(e))
        finally:
            self.buttonBox.setEnabled(1)

    @pyqtSignature("")
    def on_buttonBox_rejected(self):
        """
        Slot documentation goes here.
        """
        self.close()
