# -*- coding: utf-8 -*-
##############################################################################
#
#    Odoo, Open Source Management Solution
#    Copyright (C) 2016-TODAY Prime Consulting SA, Cape Verde (<http://prime.cv>).
#
##############################################################################

from odoo import _, api, fields, models
from odoo.exceptions import AccessError, UserError, ValidationError

class ResPartner(models.Model):
    _inherit = 'res.partner'

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        """ This function filters partners for local salesmen
        """
        context = self._context or {}
        print "CONTEXT:::::::::::::::::::"
        print context
        partners = []
        if self.user_has_groups('sales_team_extend.group_imporquimica_local'):
            query = """select p.id from res_partner p where user_id=%s"""%(self.env.user.id)
            if 'search_default_customer' in context:
                query += " and p.customer=true"
            print "QUERY::::::::::::::::::"
            print query
            self._cr.execute(query)
            result = self._cr.fetchall()
            if result:
                for res in result:
                    partners.append(res[0])
                partners = list(set(partners))
            args.append((('id','in', partners)))
        return super(ResPartner, self).search(args, offset, limit, order, count=count)

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):        
        """ This function filters partners for local salesmen
        """
        context = self._context or {}
        partners = []
        if self.user_has_groups('sales_team_extend.group_imporquimica_local'):
            query = """select p.id from res_partner p where user_id=%s"""%(self.env.user.id)
            if 'search_default_customer' in context:
                query += " and p.customer=true"
            print "QUERY::::::::::::::::::"
            print query
            self._cr.execute(query)
            result = self._cr.fetchall()
            if result:
                for res in result:
                    partners.append(res[0])
                partners = list(set(partners))
            args = [('id', 'in', partners)]
        return super(ResPartner, self).name_search(name, args, operator=operator, limit=limit)
