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

"""
Module implementing GuiSelect.
"""

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

from Ui_guiselect import Ui_GuiSelect

from PyQt4 import QtGui, QtCore
from guiconvert import GuiConvert
from guirestore import GuiRestore
import logging
import cfg, wbfs2fat

logger = logging.getLogger(__name__)

class GuiSelect(QWidget, Ui_GuiSelect):

    """
    Class documentation goes here.
    """
    def __init__(self, parent = None):
        """
        Constructor
        """
        global options
        QWidget.__init__(self, parent)
        self.setupUi(self)
        self.model = MyTableModel(self)
        self.table.setModel(self.model)
        for dev in cfg.options.dev_names:
            num,  dev = self.model.scan_dev(dev)
        self.select_best()
        QtCore.QTimer.singleShot(0, self.table.resizeRowsToContents)

    def select_best(self):
        num ,dev = self.model.get_best()
        self.table.selectRow(num)
        self.select_dev(dev)

    def select_dev(self, dev):
        self.convert.setEnabled(dev.status.convertable())
        self.restore.setEnabled(dev.status.writeable())
        self.dev_name.setText(dev.name)
        cfg.dev = dev

    @pyqtSignature("QModelIndex")
    def on_table_clicked(self, index):
        """
        Slot documentation goes here.
        """
        self.on_table_activated(index)

    @pyqtSignature("QModelIndex")
    def on_table_activated(self, index):
        """
        Slot documentation goes here.
        """
        self.select_dev(self.model.get_dev(index.row()))

    @pyqtSignature("QString")
    def on_dev_name_textEdited(self, p0):
        """
        Slot documentation goes here.
        """
        self.restore.setDisabled(1)
        self.convert.setDisabled(1)

    @pyqtSignature("")
    def on_scan_clicked(self):
        """
        Slot documentation goes here.
        """
        num, dev = self.model.scan_dev(str(self.dev_name.text()))
        self.table.selectRow(num)
        self.select_dev(dev)
        self.table.resizeRowsToContents()

    @pyqtSignature("")
    def on_scan_all_clicked(self):
        """
        Slot documentation goes here.
        """
        self.model.scan_all()
        self.select_best()
        QtCore.QTimer.singleShot(0, self.table.resizeRowsToContents)

    @pyqtSignature("")
    def on_restore_clicked(self):
        """
        Slot documentation goes here.
        """
        assert cfg.dev.name == str(self.dev_name.text())
        cfg.ui = GuiRestore()
        self.close()
        cfg.ui.show()

    @pyqtSignature("")
    def on_convert_clicked(self):
        """
        Slot documentation goes here.
        """
        assert cfg.dev.name == str(self.dev_name.text())
        cfg.ui = GuiConvert()
        self.close()
        cfg.ui.show()

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

class MyTableModel(QtCore.QAbstractTableModel): 
    def __init__(self, parent=None, *args):
        QtCore.QAbstractTableModel.__init__(self, parent, *args)
        self.headerdata = ["Device", "Status", "dev_name"]
        self.devs = [wbfs2fat.Device(*part) for part in wbfs2fat.findparts()]
        self.lookup = dict((dev.name, num) for num, dev in enumerate(self.devs))

    def rowCount(self, parent):
        return len(self.devs)

    def columnCount(self, parent):
        return 2

    def data(self, index, role):
        if not index.isValid():
            return QtCore.QVariant()
        elif role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        if index.column() == 0:
            return QtCore.QVariant(self.devs[index.row()].name)
        elif index.column() == 1:
            return QtCore.QVariant(self.devs[index.row()].status.tostr())
        elif index.column() == 2:
            return QtCore.QVariant(self.devs[index.row()].dev_name)
        return QtCore.QVariant() 

    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant(self.headerdata[col])
        return QtCore.QVariant()

    def scan_dev(self, name):
        try:
            num = self.lookup[name]
        except KeyError:
            dev = wbfs2fat.Device(name)
            num = len(self.devs)-1
            self.beginInsertRows(QtCore.QModelIndex(), num, num);
            self.devs.append(dev)
            self.lookup[name] = num
            self.endInsertRows()
        else:
            dev = self.devs[num]
        dev.scan()
#        dev.wbfs = None
        self.dataChanged.emit(self.createIndex(num,0),self.createIndex(num,self.columnCount("")-1))
        return num, dev

    def scan_all(self):
        for dev in self.devs:
            dev.scan()
#            dev.wbfs = None
        self.dataChanged.emit(self.createIndex(0,0),self.createIndex(self.rowCount("")-1, self.columnCount("")-1))

    def get_dev(self, num):
         return self.devs[num]

    def get_best(self):
        return min([(dev.status.maxmaj(), num, dev) for num, dev in enumerate(self.devs)])[1:]
