#!/usr/bin/env python

#****************************************************************************
#** $Id: sqlsubclass5.py,v 1.3 2002/07/06 13:35:41 phil Exp $
#**
#** Copyright (C) 1992-1998 Troll Tech AS.  All rights reserved.
#**
#** This file is part of an example program for PyQt.  This example
#** program may be used, distributed and modified without limitation.
#**
#*****************************************************************************/

import sys
from qt import *
from qtsql import *

from dbconnect import createConnection

TRUE  = 1
FALSE = 0

class CustomTable(QDataTable):
    def __init__(self, cursor, autoPopulate = FALSE, parent = None, name = None):
        QDataTable.__init__(self, cursor, autoPopulate, parent, name)

    def paintField(self, p, field, cr, b):
        if not field:
            return
        fn = str(field.name())
        if fn == "pricesid":
            query = QSqlQuery("SELECT name FROM prices WHERE id=%s" %
                              field.value().toString())
            value = ""
            if query.next():
                value = query.value(0).toString()
            p.drawText(2, 2, cr.width()-4, cr.height()-4,
                        self.fieldAlignment(field), value)
        elif fn == "quantity":
            p.drawText(2, 2, cr.width()-6, cr.height()-4,
                        Qt.AlignRight|Qt.AlignVCenter,  field.value().toString())
        elif fn in ("price", "cost"):
            v = field.value().toDouble()
            if v < 0:
                p.setPen(QColor("red"))
            value = QString(u"%.2f \u20ac" % v)
            p.drawText(2, 2, cr.width()-6, cr.height()-4,
                        Qt.AlignRight|Qt.AlignVCenter, value)
        elif fn == "paiddate":
            if field.value().toDate().isNull():
                v = QString("not yet")
                p.setPen(QColor("red"))
            else:
                v = field.value().toDate().toString(Qt.LocalDate)
            p.drawText(2, 2, cr.width()-4, cr.height()-4,
                        Qt.AlignHCenter|Qt.AlignVCenter, v)
        else:
            QDataTable.paintField(self, p, field, cr, b)


class InvoiceItemCursor(QSqlCursor):
    def __init__(self):
        QSqlCursor.__init__(self, "invoiceitem")

        productPrice = QSqlFieldInfo("price", QVariant.Double)
        self.append(productPrice)
        self.setCalculated(productPrice.name(), TRUE)

        productCost = QSqlFieldInfo("cost", QVariant.Double)
        self.append(productCost)
        self.setCalculated(productCost.name(), TRUE)

    def calculateField(self, name):
        fn = str(name)
        if fn == "productname":
            query = QSqlQuery("SELECT name FROM prices WHERE id=%d;" %
                              (self.field("pricesid").value().toInt()))
            if query.next():
                return query.value(0)
        elif fn == "price":
            query = QSqlQuery("SELECT price FROM prices WHERE id=%d;" %
                              (self.field("pricesid").value().toInt()))
            if query.next():
                return query.value(0)
        elif fn == "cost":
            query = QSqlQuery("SELECT price FROM prices WHERE id=%d;" %
                              (self.field("pricesid").value().toInt()))
            if query.next():
                return QVariant(query.value(0).toDouble() * 
                                self.value("quantity").toDouble())
        return QVariant(QString.null)

    def primeInsert(self):
        buffer = self.editBuffer()
        buffer.setValue("id", QVariant(0))
        buffer.setValue("paiddate", QVariant(QDate.currentDate()))
        buffer.setValue("quantity", QVariant(1))
        return buffer


class ProductPicker(QComboBox):
    def __init__(self, parent = None, name = None):
        QComboBox.__init__(self, parent, name)
        cur = QSqlCursor("prices")
        cur.select(cur.index("id"))
        while cur.next():
            self.insertItem(cur.value("name").toString(), cur.value("id").toInt())


class CustomSqlEditorFactory(QSqlEditorFactory):
    def __init__(self):
        QSqlEditorFactory.__init__(self)

    def createEditor(self, parent, field):
        try:
            if str(field.name()) == "pricesid":
                return ProductPicker(parent)
        except AttributeError:
            pass
        return QSqlEditorFactory.createEditor(self, parent, field)

class Table(CustomTable):
    def __init__(self):
        self.invoiceItemCursor = InvoiceItemCursor()
        QDataTable.__init__(self, self.invoiceItemCursor)
        self.propMap = QSqlPropertyMap()
        self.editorFactory = CustomSqlEditorFactory()
        self.propMap.insert("ProductPicker", "pricesid")
        self.installPropertyMap(self.propMap)
        self.installEditorFactory(self.editorFactory)

        for cn, ch in (("pricesid",  "Product"),
                       ("quantity",  "Quantity"),
                       ("price",     "Price" ),
                       ("cost",      "Cost"),
                       ("paiddate",  "Paid")):
            self.addColumn(cn, ch)
        self.setColumnWidth(0 , 150)
        self.setColumnWidth(1, 70)
        self.resize(600, 250)
        self.refresh()


if __name__=='__main__':
    app = QApplication(sys.argv)
    if createConnection():
        t = Table()
        app.setMainWidget(t)
        t.show()
        app.exec_loop()


