# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2015 Eficent (<http://www.eficent.com/>)
#              <contact@eficent.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, orm
from openerp.tools.translate import _


class AnalyticResourcePlanLine(orm.Model):

    _inherit = 'analytic.resource.plan.line'

    def _prepare_reservation(self, cr, uid, line, context=None):
            res = super(AnalyticResourcePlanLine,
                        self)._prepare_reservation(cr, uid, line,
                                                   context=context)
            location_obj = self.pool['stock.location']
            reseve_location_ids = location_obj.search(
                cr, uid, [('operating_unit_id', '=',
                           line.account_id.location_id.operating_unit_id.id
                           ), ('reserved', '=', True)], context=context)
            if reseve_location_ids:
                res.update({'location_dest_id': reseve_location_ids[0]})
            else:
                orm.except_orm(
                    _('Error'),
                    _('You need to define a Reservation Location assigned to '
                      'Operating Unit %s')
                    % line.account_id.location_id.operating_unit_id.name)
            return res
