from odoo import api, fields, models


class WooCategoryFilter(models.TransientModel):
    _name = 'woo.category.filter'
    _description = 'Manage Hidden Categories'

    instance_id = fields.Many2one('woo.instance', required=True)
    category_ids = fields.Many2many(
        'product.category', string='Categories to Hide',
        help='Select categories you want to hide from the unmatched products list.',
    )

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        instance_id = self.env.context.get('default_instance_id')
        if instance_id:
            instance = self.env['woo.instance'].browse(instance_id)
            res['category_ids'] = [(6, 0, instance.excluded_category_ids.ids)]
        return res

    def action_save(self):
        """Save the hidden categories to the instance."""
        self.ensure_one()
        self.instance_id.excluded_category_ids = [(6, 0, self.category_ids.ids)]
        return {'type': 'ir.actions.act_window_close'}

    def action_clear_all(self):
        """Remove all hidden categories."""
        self.ensure_one()
        self.category_ids = [(5, 0, 0)]
        return self._reopen()

    def _reopen(self):
        return {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'res_id': self.id,
            'views': [(False, 'form')],
            'target': 'new',
        }
