# -*- coding: utf-8 -*-
from odoo import models, fields, api

class HypergraphMixin(models.AbstractModel):  #абстракт для миксина
    _name = 'hg.hg_mixin'

    node_id = fields.Many2one(comodel_name='hg.node', string='Вершина графа')
    related_ids = fields.Many2many(comodel_name='hg.node', string='Связанные сущности', compute='_compute_related')
    index_ids = fields.Many2many(comodel_name='hg.index', string='Показатели', compute='_compute_indexes')

    def _compute_indexes(self):
        for s in self:
            indexes = self.env['hg.index'].search([('node_id', '=', s.node_id.id)])
            s.index_ids = [fields.Command.set(indexes.ids)]

    def _compute_related(self):
        for s in self:
            links = self.env['hg.link'].search([('source_id', '=', s.node_id.id)])
            nodes = set()
            for link in links:
                for target in link.target_ids:
                    nodes.add(target.id)
            if nodes:
                s.related_ids = [fields.Command.set(list(nodes))]
            else:
                s.related_ids = False

    @api.model_create_multi
    def create(self, vals_list):
        records = super(HypergraphMixin, self).create(vals_list)
        for res in records:
            new_node = self.env['hg.node'].create(
                {
                    'name': res.name or 'Нет имени',
                    'res_id': res.id,
                    'res_model': res._name,
                }
            )
            res.node_id = new_node
        return records
    #todo написать unlink и чистку графа
