# -*- 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 CRMLead(models.Model):
    _inherit = 'crm.lead'

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

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