from datetime import timedelta

from odoo import SUPERUSER_ID, api, fields, models
from odoo.modules.registry import Registry
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from datetime import datetime


class AccountExternalTaxMixin(models.AbstractModel):

    _name = 'account.external.tax.mixin'
    _description = 'Mixin to manage common parts of external tax calculation'

    is_tax_computed_externally = fields.Boolean(
        compute='_compute_is_tax_computed_externally',
        help='Technical field to determine if tax is calculated using an external service instead of Odoo.'
    )


    @api.depends('fiscal_position_id')
    def _compute_is_tax_computed_externally(self):
        self.is_tax_computed_externally = False

    def _get_external_taxes(self):

        return {}, {}

    def _uncommit_external_taxes(self):
        return

    def _void_external_taxes(self):
        return

    def _set_external_taxes(self, mapped_taxes, summary):

        return

    def _get_and_set_external_taxes_on_eligible_records(self):

        return

    def _get_lines_eligible_for_external_taxes(self):

        return []

    def _get_line_data_for_external_taxes(self):

        return []

    def _get_date_for_external_taxes(self):

        return


    def button_external_tax_calculation(self):
        self._get_and_set_external_taxes_on_eligible_records()
        return True

    def _enable_external_tax_logging(self, icp_name):
        self.env['ir.config_parameter'].sudo().set_param(
            icp_name,
            (fields.Datetime.now() + timedelta(minutes=30)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        )

    def _log_external_tax_request(self, module_name, icp_name, message):
        log_end_date = self.env['ir.config_parameter'].sudo().get_param(
            icp_name, ''
        )
        try:
            log_end_date = datetime.strptime(log_end_date, DEFAULT_SERVER_DATETIME_FORMAT)
            need_log = fields.Datetime.now() < log_end_date
        except ValueError:
            need_log = False
        if need_log:

            self.env.flush_all()
            dbname = self._cr.dbname
            with Registry(dbname).cursor() as cr:
                env = api.Environment(cr, SUPERUSER_ID, {})
                env['ir.logging'].create({
                    'name': module_name,
                    'type': 'server',
                    'level': 'INFO',
                    'dbname': dbname,
                    'message': message,
                    'func': '',
                    'path': '',
                    'line': '',
                })
