# -*- coding: utf-8 -*-

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


class PaymentCategoriesRegex(models.Model):
    _name = 'hms.payment.categories.regex'
    _description = 'Payment Categories Regex'

    name = fields.Char('Name', required=True)
    regex = fields.Char('Regex', required=True)
    category_id = fields.Many2one(comodel_name="hms.payment.categories", string="Category")

    def search_transactions_with_wallet_and_domestic(self, regex_patern):
        pattern = re.compile(regex_patern, re.IGNORECASE)
        transactions = self.env['brosse.bank.transactions'].search([('manually_assigned', '!=', True)])
        
        matching_transactions = []
        for transaction in transactions:
            amount = str(transaction.amount or 0)
            description = transaction.description or ''
            comment = transaction.comment or ''

            if pattern.search(amount) or pattern.search(description) or pattern.search(comment):
                matching_transactions.append(transaction)
        return matching_transactions

    def write(self, vals):
        res = super(PaymentCategoriesRegex, self).write(vals)
        matching_transactions = self.search_transactions_with_wallet_and_domestic(self.regex)

        for transaction in matching_transactions:
            transaction.write({'category_id': self.category_id.id})
        return res