# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from itertools import chain
import time
from openerp import tools
from openerp.exceptions import except_orm

class product_template(osv.Model):
    _inherit = 'product.template'
    
    def _get_default_code_csv(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = obj.default_code
        return result

    def _set_default_code_csv(self, cr, uid, id, name, value, args, context=None):
        return True

    _columns = {'ean13': fields.related('product_variant_ids', 'ean13', type='char', string='EAN13 Barcode',store=True,copy=False,readonly=True),
        'default_code': fields.related('product_variant_ids', 'default_code', type='char', string='Internal Reference',store=True,copy=False,readonly=True,select=True),
        'default_code_csv': fields.function(_get_default_code_csv,fnct_inv=_set_default_code_csv, type='char', string='Barcode'),

                }
    
    
    
       
    # setting default routes in product templates == buy and MTO
    def _get_routes(self, cr, uid, context=None):
        
        buy_route = self.pool.get('ir.model.data').xmlid_to_res_id(cr, uid, 'purchase.route_warehouse0_buy')
        mto_route = self.pool.get('ir.model.data').xmlid_to_res_id(cr, uid, 'stock.route_warehouse0_mto')
        if buy_route and not mto_route:
            return [buy_route]
        if mto_route and not buy_route:
            return [mto_route]
        if buy_route and mto_route:
            return [mto_route,buy_route]
        return []

    _defaults = {
        'route_ids': _get_routes,
    }
    
    
    def onchange_type(self, cr, uid, ids, type):
        res = super(product_template, self).onchange_type(cr, uid, ids, type)
        if type in ('consu', 'service'):
            res = {'value': {'route_ids': []}}
        if type in ('product'):
            res = {'value': {'route_ids': self._get_routes(cr, uid, context=None)}}
        return res
    
    
class product_product(osv.Model):
    _inherit = 'product.product'
    
    _columns = {'ean13': fields.char('EAN13 Barcode', size=13, help="International Article Number used for product identification.",copy=False,readonly=True),
        'default_code' : fields.char('Internal Reference', select=True,copy=False,readonly=True),
        
                }
    
    def onchange_type(self, cr, uid, ids, type):
        res = super(product_product, self).onchange_type(cr, uid, ids, type)
        if type in ('consu', 'service'):
            res = {'value': {'route_ids': []}}
        if type in ('product'):
            res = {'value': {'route_ids': self.pool.get('product.template')._get_routes(cr, uid, context=None)}}
        return res
    

    def copy(self, cr, uid, id, default=None, context=None):
        raise except_orm(('Forbidden'),("Please Duplicate Record From \"Product Main\" Menu"))
        return super(product_product, self).copy(cr, uid, id, default=default, context=context)
    
    def name_get(self, cr, uid, ids, context=None):
        res = super(product_product, self).name_get(cr, uid, ids, context)
        #print "-=-=in name_get product_product=-=-",context,res
        res_new=[]
        if context.get('cust_inv_name_get',False):
            for rec in res:
                if rec and not rec[1]:continue
                attrs=''
                p_obj=self.pool.get('product.product').browse(cr,uid,rec[0],context)
                attrs=(attrs +str(p_obj.panipat_brand_name.name)) if p_obj.panipat_brand_name.name else ''
                new_name=rec[1] +' ['+attrs+']' if attrs else rec[1]
                res_new.append((rec[0],new_name))
            #print "--res_new=-=in name_get product_product=-=-",res_new
            if res_new:return res_new

        for rec in res:
            if rec and not rec[1]:continue
            attrs=''
            p_obj=self.pool.get('product.product').browse(cr,uid,rec[0],context)
            attrs=(attrs + ' '+str(p_obj.panipat_brand_name.name)) if p_obj.panipat_brand_name.name else ''
            attrs=(attrs + ';'+str(p_obj.vol_file_name.name)) if p_obj.vol_file_name.name else ''
            if p_obj.serial_no:
                attrs=attrs + ' (S/No-'+str(p_obj.serial_no)+')'
            if p_obj.shade_no:
                attrs=attrs + ' (Sh/No-'+str(p_obj.shade_no)+')'
            if p_obj.design_code:
                attrs=attrs + ' (D/No-'+str(p_obj.design_code)+')'
            if p_obj.color_code:
                attrs=attrs + ' (Co/Co-'+str(p_obj.color_code)+')'
            if p_obj.other_code:
                attrs=attrs + ' (Ot/Co-'+str(p_obj.other_code)+')'
            if not (p_obj.serial_no and p_obj.shade_no and p_obj.design_code and p_obj.color_code and p_obj.other_code) and  p_obj.color_name:
                attrs=attrs + ' (Color-'+str(p_obj.color_name)+')'
            new_name=rec[1] +' ['+attrs+']' if attrs else rec[1]
            res_new.append((rec[0],new_name))
        #print "--res_new=-=in name_get product_product=-=-",res_new
        if res_new:return res_new
        return res
        
class product_pricelist(osv.osv):
    inherit="product.pricelist"
    
    # line added to check for further rules in pricelist version if price is false
    # eg. if rule is to check for supplier prices and there's no supplier associated with product then
    # instead of giving price as False it'll check for further rules
    def _price_rule_get_multi(self, cr, uid, pricelist, products_by_qty_by_partner, context=None):
        context = context or {}
        date = context.get('date') or time.strftime('%Y-%m-%d')
        date = date[0:10]

        products = map(lambda x: x[0], products_by_qty_by_partner)
        currency_obj = self.pool.get('res.currency')
        product_obj = self.pool.get('product.template')
        product_uom_obj = self.pool.get('product.uom')
        price_type_obj = self.pool.get('product.price.type')

        if not products:
            return {}

        version = False
        for v in pricelist.version_id:
            if ((v.date_start is False) or (v.date_start <= date)) and ((v.date_end is False) or (v.date_end >= date)):
                version = v
                break
        if not version:
            raise osv.except_osv(_('Warning!'), _("At least one pricelist has no active version !\nPlease create or activate one."))
        categ_ids = {}
        for p in products:
            categ = p.categ_id
            while categ:
                categ_ids[categ.id] = True
                categ = categ.parent_id
        categ_ids = categ_ids.keys()

        is_product_template = products[0]._name == "product.template"
        if is_product_template:
            prod_tmpl_ids = [tmpl.id for tmpl in products]
            # all variants of all products
            prod_ids = [p.id for p in
                        list(chain.from_iterable([t.product_variant_ids for t in products]))]
        else:
            prod_ids = [product.id for product in products]
            prod_tmpl_ids = [product.product_tmpl_id.id for product in products]

        # Load all rules
        cr.execute(
            'SELECT i.id '
            'FROM product_pricelist_item AS i '
            'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = any(%s)) '
                'AND (product_id IS NULL OR (product_id = any(%s))) '
                'AND ((categ_id IS NULL) OR (categ_id = any(%s))) '
                'AND (price_version_id = %s) '
            'ORDER BY sequence, min_quantity desc',
            (prod_tmpl_ids, prod_ids, categ_ids, version.id))
        
        item_ids = [x[0] for x in cr.fetchall()]
        items = self.pool.get('product.pricelist.item').browse(cr, uid, item_ids, context=context)

        price_types = {}

        results = {}
        for product, qty, partner in products_by_qty_by_partner:
            results[product.id] = 0.0
            rule_id = False
            price = False

            # Final unit price is computed according to `qty` in the `qty_uom_id` UoM.
            # An intermediary unit price may be computed according to a different UoM, in
            # which case the price_uom_id contains that UoM.
            # The final price will be converted to match `qty_uom_id`.
            qty_uom_id = context.get('uom') or product.uom_id.id
            price_uom_id = product.uom_id.id
            qty_in_product_uom = qty
            if qty_uom_id != product.uom_id.id:
                try:
                    qty_in_product_uom = product_uom_obj._compute_qty(
                        cr, uid, context['uom'], qty, product.uom_id.id or product.uos_id.id)
                except except_orm:
                    # Ignored - incompatible UoM in context, use default product UoM
                    pass

            for rule in items:
                #print "rule==",rule
                if rule.min_quantity and qty_in_product_uom < rule.min_quantity:
                    continue
                if is_product_template:
                    if rule.product_tmpl_id and product.id != rule.product_tmpl_id.id:
                        continue
                    if rule.product_id and \
                            (product.product_variant_count > 1 or product.product_variant_ids[0].id != rule.product_id.id):
                        # product rule acceptable on template if has only one variant
                        continue
                else:
                    if rule.product_tmpl_id and product.product_tmpl_id.id != rule.product_tmpl_id.id:
                        continue
                    if rule.product_id and product.id != rule.product_id.id:
                        continue

                if rule.categ_id:
                    cat = product.categ_id
                    while cat:
                        if cat.id == rule.categ_id.id:
                            break
                        cat = cat.parent_id
                    if not cat:
                        continue

                if rule.base == -1:
                    if rule.base_pricelist_id:
                        price_tmp = self._price_get_multi(cr, uid,
                                rule.base_pricelist_id, [(product,
                                qty, partner)], context=context)[product.id]
                        ptype_src = rule.base_pricelist_id.currency_id.id
                        price_uom_id = qty_uom_id
                        price = currency_obj.compute(cr, uid,
                                ptype_src, pricelist.currency_id.id,
                                price_tmp, round=False,
                                context=context)
                elif rule.base == -2:
                    seller = False
                    for seller_id in product.seller_ids:
                        if (not partner) or (seller_id.name.id != partner):
                            continue
                        seller = seller_id
                    if not seller and product.seller_ids:
                        seller = product.seller_ids[0]
                    if seller:
                        qty_in_seller_uom = qty
                        seller_uom = seller.product_uom.id
                        if qty_uom_id != seller_uom:
                            qty_in_seller_uom = product_uom_obj._compute_qty(cr, uid, qty_uom_id, qty, to_uom_id=seller_uom)
                        price_uom_id = seller_uom
                        for line in seller.pricelist_ids:
                            if line.min_quantity <= qty_in_seller_uom:
                                price = line.price

                else:
                    if rule.base not in price_types:
                        price_types[rule.base] = price_type_obj.browse(cr, uid, int(rule.base))
                    price_type = price_types[rule.base]

                    # price_get returns the price in the context UoM, i.e. qty_uom_id
                    price_uom_id = qty_uom_id
                    price = currency_obj.compute(
                            cr, uid,
                            price_type.currency_id.id, pricelist.currency_id.id,
                            product_obj._price_get(cr, uid, [product], price_type.field, context=context)[product.id],
                            round=False, context=context)
                    #print "in9898989898===",cr, uid, [product], price_type.field, context,[price]

                if price is not False:
                    price_limit = price
                    price = price * (1.0+(rule.price_discount or 0.0))
                    if rule.price_round:
                        price = tools.float_round(price, precision_rounding=rule.price_round)

                    convert_to_price_uom = (lambda price: product_uom_obj._compute_price(
                                                cr, uid, product.uom_id.id,
                                                price, price_uom_id))
                    if rule.price_surcharge:
                        price_surcharge = convert_to_price_uom(rule.price_surcharge)
                        price += price_surcharge

                    if rule.price_min_margin:
                        price_min_margin = convert_to_price_uom(rule.price_min_margin)
                        price = max(price, price_limit + price_min_margin)

                    if rule.price_max_margin:
                        price_max_margin = convert_to_price_uom(rule.price_max_margin)
                        price = min(price, price_limit + price_max_margin)

                    rule_id = rule.id
                
                # line added to check for further rules in pricelist version if price is false
                if price is False:
                    continue
                #print "in price calculation by pricelist ",price," items=",items
                break

            # Final price conversion to target UoM
            price = product_uom_obj._compute_price(cr, uid, price_uom_id, price, qty_uom_id)

            results[product.id] = (price, rule_id)
        return results
 