# Copyright (C) 2021: Criptomart (https://criptomart.net)
# @author Santi Noreña (<santi@criptomart.net>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

#import logging

from odoo import tools, models, fields, api, _

#_logger = logging.getLogger(__name__)

class ProductTemplate(models.Model):
    _inherit = "product.template"

    @api.multi
    def create_stock_picking(self):
        picking_vals = self.env['stock.picking'].default_get(self.env['stock.picking']._fields.keys())
        picking_vals.update({
                'picking_type_id' : self.env.ref('stock.picking_type_internal').id,
                'location_id': self.env.ref('stock.stock_location_stock').id,
                'location_dest_id': self.env.ref('stock.stock_location_stock').id,
        })
        picking = self.env['stock.picking'].create(picking_vals)

        for p in self:
          if p.qty_available > 0:
            move_vals = {
                'name': p.name,
                'product_id': p.product_variant_id.id,
                'product_uom_qty': p.qty_available,
                'product_uom': p.uom_id.id,
                'picking_id': picking.id,
                'location_id': self.env.ref('stock.stock_location_stock').id,
                'location_dest_id': self.env.ref('stock.stock_location_stock').id,
                'state': 'draft',
            }
            picking.move_lines = [(0, 0, move_vals)]

        views = [(self.env.ref('stock.view_picking_form').id, 'form')]
        return {
                'type': 'ir.actions.act_window',
                'res_model': 'stock.picking',
                'res_id': picking.id,
                'target': 'current',
                'views': views,
        }
