# -*- coding: utf-8 -*-
from odoo import models, fields, api, modules, tools
from odoo.tools import config
from docutils.core import publish_string
from odoo.addons.base.module.module import MyWriter
import lxml.html
import odoo


class Module(models.Model):
    _inherit = 'ir.module.module'
    _description = "Module Inherit"

    @api.multi
    def button_upgrade_wizard(self):
        if not MODULE_DEPLOY_PSD:
            return self.button_immediate_upgrade()
        else:
            return {
                'name': '模块部署密码输入框',
                'type': 'ir.actions.act_window',
                'model': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'jd.init.wizard.module.deploy',
                'target': 'new',
                'view_id': False,
                'context': {
                    'module_id': self.id,
                    'action': 'upgrade'
                }
            }

    # 重写_get_desc方法，解决description中文乱码问题
    @api.depends('name', 'description')
    def _get_desc(self):
        for module in self:
            path = modules.get_module_resource(module.name, 'static/description/index.html')
            if path:
                with tools.file_open(path, 'rb') as desc_file:
                    doc = desc_file.read().decode('utf-8')
                    html = lxml.html.document_fromstring(doc)
                    for element, attribute, link, pos in html.iterlinks():
                        if element.get('src') and not '//' in element.get('src') and not 'static/' in element.get(
                                'src'):
                            element.set('src', "/%s/static/description/%s" % (module.name, element.get('src')))
                    module.description_html = tools.html_sanitize(lxml.html.tostring(html))
            else:
                overrides = {
                    'embed_stylesheet': False,
                    'doctitle_xform': False,
                    'output_encoding': 'unicode',
                    'xml_declaration': False,
                    'file_insertion_enabled': False,
                }
                output = publish_string(source=module.description or '', settings_overrides=overrides,
                                        writer=MyWriter())
                module.description_html = tools.html_sanitize(output)