# -*- coding: utf-8 -*-
from odoo import models, api, fields, modules
from odoo.addons.base.module import module
from odoo.tools import config
from odoo.exceptions import ValidationError

MODULE_DEPLOY_PSD = config.get('modules_deploy_password')


class WizardModuleDeploy(models.TransientModel):
    """
    模块部署Wizard
    """
    _name = 'jd.init.wizard.module.deploy'
    _description = u'模块部署密码输入框'
    _order = 'id asc'

    module_id = fields.Many2one('ir.module.module', string=u'部署模块', readonly=True)
    action = fields.Selection([('install', u'安装'), ('uninstall', u'卸载'), ('upgrade', u'升级'), ('disable', u'停用')],
                              string=u'部署类型', readonly=True)
    password = fields.Char(string=u'部署密码', required=True)

    @api.model
    def default_get(self, fields):
        res = super(WizardModuleDeploy, self).default_get(fields)
        module_id = self.env.context.get('module_id', None)
        action = self.env.context.get('action', None)
        res.update({
            'module_id': module_id,
            'action': action
        })
        return res

    @api.multi
    def button_module_deploy(self):
        if MODULE_DEPLOY_PSD:
            if MODULE_DEPLOY_PSD == self.password:
                module_id = self.module_id
                if self.action == 'install':
                    return module_id.button_immediate_install()
                elif self.action == 'uninstall':
                    return module_id.button_uninstall()
                elif self.action == 'upgrade':
                    return module_id.button_immediate_upgrade()
            else:
                raise ValidationError(u'部署密码错误')
        else:
            module_id = self.module_id
            if self.action == 'install':
                return module_id.button_immediate_install()
            elif self.action == 'uninstall':
                return module_id.button_uninstall()
            elif self.action == 'upgrade':
                return module_id.button_immediate_upgrade()
