# Copyright 2021 Criptomart
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)

#import logging

from odoo import api, models, fields
from odoo.exceptions import ValidationError

#_logger = logging.getLogger(__name__)

class PickingType(models.Model):
    _inherit = 'stock.picking.type'

    is_deposit = fields.Boolean(
        string='Depósito',
        help='Éste albarán es un depósito, no es una venta final.',
        default= False, 
    )

class Picking(models.Model):
    _inherit = 'stock.picking'

    @api.onchange('picking_type_id','partner_id')
    def onchange_picking_type(self):
       super(Picking, self).onchange_picking_type()
       if self.picking_type_id.is_deposit and self.partner_id:
           self.change_dest_location()
       if self.partner_id and self.location_id == self.env.ref("stock_picking_deposito.stock_location_deposits_stock"):
           self.update({
               'location_id': self.partner_id.deposit_sale_location_id.id,
           })

    def change_dest_location(self):
        if self.picking_type_id.code == 'internal':
            if  not self.partner_id.deposit_sale_accept:
                raise ValidationError("Éste cliente no acepta material en depósito, configúralo antes de crear un depósito para él.")
                return
            self.update({
                'location_dest_id': self.partner_id.deposit_sale_location_id.id,
            })
        elif self.picking_type_id.code == 'incoming':
            if not self.partner_id.deposit_buy_accept:
                raise ValidationError("Éste proveedor no suministra material en depósito, configúralo antes de crear un depósito para él.")
                return
            self.update({
                'location_dest_id': self.partner_id.deposit_buy_location_id.id,
            })

