# Copyright 2020 Creu Blanca
# Copyright 2024 Tecnativa - Víctor Martínez
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

from odoo import api, fields, models
from odoo.tools import config


class DMSFieldMixin(models.AbstractModel):
    _name = "dms.field.mixin"
    _description = "Mixin to use DMS Field"

    dms_directory_ids = fields.One2many(
        "dms.directory",
        "res_id",
        string="DMS Directories",
        domain=lambda self: [
            ("res_model", "=", self._name),
            ("storage_id.save_type", "!=", "attachment"),
        ],
        auto_join=True,
    )

    @api.model
    def models_to_track_dms_field_template(self):
        """Models to be tracked for dms field templates
        :args:
        :returns: list of models
        """
        return self.env["dms.field.template"].sudo().search([]).mapped("model_id.model")

    @api.model_create_multi
    def create(self, vals_list):
        """Create a dms directory when creating the record if exist a template.
        We need to avoid applying a template except when testing functionality
        with dms_field* modules to avoid the error that a directory with the same
        name already exists (example: create partner).
        """
        result = super().create(vals_list)
        test_condition = not config["test_enable"] or self.env.context.get(
            "test_dms_field"
        )
        if (
            test_condition
            and not self.env.context.get("skip_track_dms_field_template")
            and self._name in self.models_to_track_dms_field_template()
        ):
            template = self.env["dms.field.template"].with_context(res_model=self._name)
            for item in result:
                template.with_context(res_id=item.id).create_dms_directory()
        return result

    def write(self, vals):
        """When modifying a record that has linked directories and changing the
        user_id field it is necessary to update the auto-generated access group
        (name and explicit_user_ids).
        """
        res = super().write(vals)
        # Apply sudo() in case the user does not have access to the directory
        for item in self.sudo().filtered("dms_directory_ids"):
            if "user_id" in vals:
                template = self.env["dms.field.template"]._get_template_from_model(
                    item._name
                )
                if template:
                    template.sudo()._get_autogenerated_group(item)
        return res

    def unlink(self):
        """When deleting a record, we also delete the linked directories and the
        auto-generated access group.
        """
        # Apply sudo() in case the user does not have access to the directory
        for record in self.sudo().filtered("dms_directory_ids"):
            group = (
                self.env["dms.access.group"].sudo()._get_item_from_dms_field_ref(record)
            )
            record.sudo().dms_directory_ids.unlink()
            group.unlink()
        return super().unlink()
