import sys
import os
from PyQt4.QtSql import *
import ui_forms.ui_receiveform
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sqlalchemy import  *
from sqlalchemy.orm import *
from databaseschema import *
import modelsandviews
import genericdelegates
from functions import *

localTITLE = "Receiving"

#==============================================================================
### Model Setup ============== 
(ITEM, DESCRIPTION, QTY, PRICE, SHIPPING, COST, TOTAL, CAD_TOTAL, MEMO) = range(9)

class ReceivingDetailModel(QAbstractTableModel):
 
### Model Initializer ==============    
    def __init__(self, session, parent=None):
        super(ReceivingDetailModel, self).__init__(parent)
        self.records = []
        self.records.append(ReceiveRMD())
        self.shippingRate = 0
        self.currencyRate = 1
        self.journal_date = None
        self.session = session
        
    def setDate(self, date):
        self.journal_date = date

### Base Implemantations ==============   
    def rowCount(self, index=QModelIndex()):
        return len(self.records)
    
    def columnCount(self, index=QModelIndex()):
        return 9
    
    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole:
            return QVariant()
        if orientation == Qt.Horizontal:
            if section == ITEM:
                return QVariant("Item")
            elif section == DESCRIPTION:
                return QVariant("Description")
            elif section == QTY:
                return QVariant('Qty (KG,LT)')
            elif section == PRICE:
                return QVariant("Price")
            elif section == SHIPPING:
                return QVariant("Shipping")
            elif section == COST:
                return QVariant("Cost")
            elif section == TOTAL:
                return QVariant("Total")
            elif section == MEMO:
                return QVariant("Memo")
            elif section == CAD_TOTAL:
                return QVariant('CAD Total')
        return QVariant(section + 1)
    
    def flags(self, index):
        flag = QAbstractTableModel.flags(self, index)
        if index.column() not in (COST, SHIPPING, CAD_TOTAL):
            flag |= Qt.ItemIsEditable
        return flag
    
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or not (0 <= index.row() < len(self.records)):
            return QVariant()
        record = self.records[index.row()]
        column = index.column()
        if role == Qt.DisplayRole:
            if column == ITEM:
                item_no = dLookup(BOM.bom_no, BOM.bom_id==record.bom_id)
                return QVariant(item_no)
            elif column == DESCRIPTION:
                return QVariant(record.rmd_desc)
            elif column == QTY:
                if not record.qty:
                    return QVariant(record.qty)
                return QVariant(round(record.qty, 4))
            elif column == PRICE:
                if not record.cost_native:
                    return QVariant(record.cost_native)
                return QVariant(round(getType(record.cost_native), 4))
            elif column == SHIPPING:
                if not record.rmd_shipping:
                    return QVariant(record.rmd_shipping)
                return QVariant(round(getType(record.rmd_shipping), 2))
            elif column == COST:
                if not record.cost:
                    return QVariant(record.cost)
                return QVariant(round(getType(record.cost), 2))
            elif column == TOTAL:
                if not record.native_total:
                    return QVariant(record.native_total)
                return QVariant(round(getType(record.native_total), 2))
            elif column == CAD_TOTAL:
                if not record.total:
                    return QVariant(record.total)
                return QVariant(round(getType(record.total), 2))
            elif column == MEMO:
                return QVariant(record.rmd_memo)
        return QVariant()
        
    def setData(self, index, value, role=Qt.EditRole):
        if index.isValid() and role == Qt.EditRole:
            record = self.records[index.row()]
            column = index.column()
            if column == ITEM:
                item = value.toInt()[0]
                record.bom_id = item
                record.rmd_desc = dLookup(BOM.bom_desc, 
                                                     BOM.bom_id==item)
                record.cost_native = dLookup(BOM.bom_cost, 
                                                 BOM.bom_id==item)
                self.checkPrice(record)
            elif column == DESCRIPTION:
                record.rmd_desc = value.toString()
            elif column == QTY:
                qty, ok = value.toFloat()
                if not ok:
                    return False
                record.qty = qty
                record.rmd_shipping = self.calcShipping(record)
                record.cost = self.calcCost(record)
                record.native_total = self.calcNTotal(record)
                record.total = self.calcTotal(record)
            elif column == PRICE:
                price, ok = value.toFloat()
                if not ok:
                    return False
                record.cost_native = price
                record.rmd_shipping = self.calcShipping(record)
                record.cost = self.calcCost(record)
                record.native_total = self.calcNTotal(record)
                record.total = self.calcTotal(record)