import base64
import hashlib
import os
import re

from odoo import models, fields, http, api, _
from odoo.modules.module import get_resource_path, get_module_path
from odoo.tools.mimetypes import guess_mimetype
from odoo.tools import consteq, pycompat


class InheritIrHttp(models.AbstractModel):
    _inherit = 'ir.http'

    @classmethod
    def _binary_ir_attachment_redirect_content(cls, record, default_mimetype='application/octet-stream'):
        # mainly used for theme images attachemnts
        base = http.request.env['ir.config_parameter'].sudo().get_param('web.base.url', '')
        if record.type == 'url' and record.url and base.startswith("https") and "http://121.37.69.162:9000" in record.url:
            filename = filehash = None
            mimetype = getattr(record, 'mimetype', False)
            url = record.url.replace("http://121.37.69.162:9000", "https://minio.xbg.rokeris.com")
            status = 301
            content = url
        else:
            status = content = filename = filehash = None
            mimetype = getattr(record, 'mimetype', False)
            if record.type == 'url' and record.url:
                # if url in in the form /somehint server locally
                url_match = re.match("^/(\w+)/(.+)$", record.url)
                if url_match:
                    module = url_match.group(1)
                    module_path = get_module_path(module)
                    module_resource_path = get_resource_path(module, url_match.group(2))

                    if module_path and module_resource_path:
                        module_path = os.path.join(os.path.normpath(module_path),
                                                   '')  # join ensures the path ends with '/'
                        module_resource_path = os.path.normpath(module_resource_path)
                        if module_resource_path.startswith(module_path):
                            with open(module_resource_path, 'rb') as f:
                                content = base64.b64encode(f.read())
                            status = 200
                            filename = os.path.basename(module_resource_path)
                            mimetype = guess_mimetype(base64.b64decode(content), default=default_mimetype)
                            filehash = '"%s"' % hashlib.md5(pycompat.to_text(content).encode('utf-8')).hexdigest()

                if not content:
                    status = 301
                    content = record.url
        return status, content, filename, mimetype, filehash
