from odoo import fields, models


class EstimateWizard(models.Model):
    _name = "estimate.wizard"

    template_id = fields.Many2one(comodel_name='hg.templates', string='Шаблон сметы', required=True)
    code_id = fields.Many2one(comodel_name='hg.index.code', string='Код показателей', required=True)

    def confirm_action(self):
        self.ensure_one()
        task = self.env.context.get('active_id') and self.env['project.task'].browse(self.env.context['active_id'])
        if not task:
            return
        for line in self.template_id.line_ids:
            node = self._get_node(res_model='project.task', res_id=task.id, name=task.name)
            index = self.env['hg.index'].create({
                'node_id': node.id,
                'name': line.index_id.name,
                'internal_code_id': self.code_id.id,
            })
            self.env['hg.value'].create({
                'index_id': index.id,
                'type': 'alone',
                'date_due': line.date_due,
                'value_float_plan': line.value_float_plan,
            })
        return {'type': 'ir.actions.act_window_close'}


    def _get_node(self, res_model, res_id, name):
        Node = self.env['hg.node']

        node = Node.search([
            ('res_model', '=', res_model),
            ('res_id', '=', res_id)
        ], limit=1)

        if not node:
            node = Node.create({
                'name': name,
                'res_model': 'project.task',
                'res_id': res_id,
            })
        return node
