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

#import logging

from odoo import _, api, fields, models

#_logger = logging.getLogger(__name__)

class ProductProduct(models.Model):
    _inherit = 'product.product'


    @api.model
    def create(self, vals):
        category = self.env['product.category']
        categ_id = vals.get("categ_id")
        template_id = vals.get("product_tmpl_id")
        if categ_id:
            category = category.browse(categ_id)
            vals['pos_categ_id'] = self.get_category_pos_category(category)
            vals['available_in_pos'] = True 
        elif template_id:
            template = self.env["product.template"].browse(template_id)
            category = template.categ_id
            template.pos_categ_id = self.get_category_pos_category(category)
            if template.pos_categ_id:
                template.available_in_pos = True

        return super().create(vals)

    @api.model
    def get_category_pos_category(self, category=False):
        cat = category
        if self.env.user.company_id.use_parent_categories_to_determine_pos_categ:
            while not cat.pos_categ_id and cat.parent_id:
                cat = cat.parent_id

        return cat.pos_categ_id
        
