# -*- 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 AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        """ This function filters invoices for local salesmen
        """
        context = self._context or {}
        print "CONTEXT:::::::::::::::::::"
        print context
        invoices = []
        if self.user_has_groups('sales_team_extend.group_imporquimica_local'):
            if 'type' in context:
                if context['type'] == 'out_invoice':
                    query = """select i.id from account_invoice i where i.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:
                            invoices.append(res[0])
                        invoices = list(set(invoices))
                    args.append((('id','in', invoices)))
        return super(AccountInvoice, self).search(args, offset, limit, order, count=count)

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):        
        """ This function filters invoices for local salesmen
        """
        context = self._context or {}
        invoices = []
        if self.user_has_groups('sales_team_extend.group_imporquimica_local'):
            if 'type' in context:
                if context['type'] == 'out_invoice':
                    query = """select i.id from account_invoice i where i.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:
                            invoices.append(res[0])
                        invoices = list(set(invoices))
                    args = [('id', 'in', invoices)]
        return super(AccountInvoice, self).name_search(name, args, operator=operator, limit=limit)
