from odoo import api, fields, models


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

    @api.model
    def create(self, vals):
        categ_id = vals.get("categ_id")
        template_id = vals.get("product_tmpl_id")
        if categ_id:
            #check if there are public categories setup by user
            new_cats = []
            old_cats = vals.get("public_categ_ids")
            if old_cats:
              if old_cats[0][2]:
                for i in old_cats[0][2]:
                    new_cats.append(i)
            category = self.env['product.category'].browse(categ_id)
            pub_cat = self.get_category_public_category(category).id
            if pub_cat:
                new_cats.append(pub_cat)
            vals['public_categ_ids'] = [[6,0,new_cats]]
        elif template_id:
            template = self.env["product.template"].browse(template_id)
            category = template.categ_id
            pub_cat = self.get_category_public_category(category)
            if pub_cat:
                template.public_categ_ids += pub_cat

        return super().create(vals)

    @api.model
    def get_category_public_category(self, category=False):
        cat = category
        if not cat.public_categ_id and self.env.user.company_id.use_parent_categories_to_determine_public_cat:
            while not cat.public_categ_id and cat.parent_id:
                cat = cat.parent_id
        return cat.public_categ_id
