import ast
from typing import Any, Dict, Optional

from odoo import models

from . import base


class MailTemplate(base.Converter):
    """This converter wraps ``mail.template::_render_template``.
    Multiple records are allowed but ``mail.template::render_template`` still
    runs once per record; to accomodate, we provide ``ctx["records"]``.
    """

    def __init__(self, template: str, post_eval: bool = False):
        self.template = template
        self.post_eval = post_eval

    def odoo_to_message(
        self, records: models.Model, ctx: Optional[Dict] = None
    ) -> Any:
        multiple_records = len(records) > 1
        record_ids_or_id = records.ids if multiple_records else records.id
        value = (
            records.env["mail.template"]
            .with_context(records=records, safe=True)
            ._render_template(self.template, records._name, record_ids_or_id)
        )
        if multiple_records:  # render_template outputs indexed by record ID
            value = value[records[0].id]
        if self.post_eval:
            value = ast.literal_eval(value)
        return value