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

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _

import odoo.addons.decimal_precision as dp

class SaleOrder(models.Model):
    _inherit = "sale.order"

    @api.model
    def _default_warehouse_id_custom(self):
        print "Default warehouse:::::::::::::::::::::::::::::::::::::::::"
        warehouse_id = False
        company = self.env.user.company_id.id
        user_id = self.env.user.id
        team_id = self.env['crm.team'].sudo().search(['|', ('user_id', '=', user_id), ('member_ids', '=', user_id)],limit=1)
        if team_id:
            if team_id.warehouse_id:
                warehouse_id = team_id.warehouse_id.id
                warehouse_ids = self.env['stock.warehouse'].search([('id', '=', warehouse_id)], limit=1)
            else:
                warehouse_ids = self.env['stock.warehouse'].search([('company_id', '=', company)], limit=1)
        else:
            warehouse_ids = self.env['stock.warehouse'].search([('company_id', '=', company)], limit=1)
        return warehouse_ids

    @api.model
    def _default_account_journal_id(self):
        print "Default account journal:::::::::::::::::::::::::::::::::::::::::"
        account_journal_id = False
        user_id = self.env.user.id
        team_id = self.env['crm.team'].sudo().search(['|', ('user_id', '=', user_id), ('member_ids', '=', user_id)],limit=1)
        if team_id:
            if team_id.sales_journal_id:
                account_journal_id = team_id.sales_journal_id.id
                journal_ids = self.env['account.journal'].search([('id', '=', account_journal_id)], limit=1)
            else:
                journal_ids = self.env['account.journal'].search([('type','=','sale')], limit=1)
        else:
            journal_ids = self.env['account.journal'].search([('type','=','sale')], limit=1)
        return journal_ids

    warehouse_id = fields.Many2one(
        'stock.warehouse', string='Warehouse',
        required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
        default=_default_warehouse_id_custom)
    account_journal_id = fields.Many2one('account.journal', 'Sales Journal', domain=[('type','=','sale')], default=_default_account_journal_id)

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

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