#!/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 PyTQt.  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(TQDataTable):
    def __init__(self, cursor, autoPopulate = FALSE, parent = None, name = None):
        TQDataTable.__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 = TQSqlQuery("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,
                        TQt.AlignRight|TQt.AlignVCenter,  field.value().toString())
        elif fn in ("price", "cost"):
            v = field.value().toDouble()
            if v < 0:
                p.setPen(TQColor("red"))
            value = TQString(u"%.2f \u20ac" % v)
            p.drawText(2, 2, cr.width()-6, cr.height()-4,
                        TQt.AlignRight|TQt.AlignVCenter, value)
        elif fn == "paiddate":
            if field.value().toDate().isNull():
                v = TQString("not yet")
                p.setPen(TQColor("red"))
            else:
                v = field.value().toDate().toString(TQt.LocalDate)
            p.drawText(2, 2, cr.width()-4, cr.height()-4,
                        TQt.AlignHCenter|TQt.AlignVCenter, v)
        else:
            TQDataTable.paintField(self, p, field, cr, b)


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

        productPrice = TQSqlFieldInfo("price", TQVariant.Double)
        self.append(productPrice)
        self.setCalculated(productPrice.name(), TRUE)

        productCost = TQSqlFieldInfo("cost", TQVariant.Double)
        self.append(productCost)
        self.setCalculated(productCost.name(), TRUE)

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

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


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


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

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

class Table(CustomTable):
    def __init__(self):
        self.invoiceItemCursor = InvoiceItemCursor()
        TQDataTable.__init__(self, self.invoiceItemCursor)
        self.propMap = TQSqlPropertyMap()
        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 = TQApplication(sys.argv)
    if createConnection():
        t = Table()
        app.setMainWidget(t)
        t.show()
        app.exec_loop()