# -*- coding: utf-8 -*-
#############################################################################
#
#    Changsha Yizuo Intelligent Technology Co., Ltd.
#
#    Copyright (C) 2020-TODAY Yizuo Intelligent Technology.(<https://www.yizuo.ltd>).
#    Author: Van(v16)(pengyb@yizuo.ltd)
#
#    You can modify it under the terms of the GNU AFFERO
#    GENERAL PUBLIC LICENSE (AGPL v3), Version 3.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU AFFERO GENERAL PUBLIC LICENSE (AGPL v3) for more details.
#
#    You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
#    (AGPL v3) along with this program.
#    If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
try:
    import httpagentparser
except ImportError:
    pass
from time import gmtime, strftime
from odoo.addons.web.controllers import home
from odoo.http import request
from odoo.exceptions import Warning
import odoo
import odoo.modules.registry
from odoo.tools.translate import _
from odoo import http


class Home(home.Home):

    @http.route('/web/login', type='http', auth="none")
    def web_login(self, redirect=None, **kw):
        home.ensure_db()
        request.params['login_success'] = False
        if request.httprequest.method == 'GET' and redirect and request.session.uid:
            return request.redirect(redirect)

        # so it is correct if overloaded with auth="public"
        if not request.uid:
            request.update_env(user=odoo.SUPERUSER_ID)

        # values = {k: v for k, v in request.params.items() if k in SIGN_UP_REQUEST_PARAMS}
        values = request.params.copy()
        try:
            values['databases'] = http.db_list()
        except odoo.exceptions.AccessDenied:
            values['databases'] = None

        if request.httprequest.method == 'POST':
            try:
                uid = request.session.authenticate(request.db, request.params['login'], request.params['password'])
                request.params['login_success'] = True
                return request.redirect(self._login_redirect(uid, redirect=redirect))
            except odoo.exceptions.AccessDenied as e:
                if e.args == odoo.exceptions.AccessDenied().args:
                    values['error'] = _("密码输入错误")
                else:
                    values['error'] = e.args[0]
        else:
            if 'error' in request.params and request.params.get('error') == 'access':
                values['error'] = _('Only employees can access this database. Please contact the administrator.')

        if 'login' not in values and request.session.get('auth_login'):
            values['login'] = request.session.get('auth_login')

        if not odoo.tools.config['list_db']:
            values['disable_database_manager'] = True

        # get confi login set
        param_obj = request.env['ir.config_parameter'].sudo()
        values['reset_password_enabled'] = param_obj.get_param('auth_signup.reset_password')
        values['signup_enabled'] = param_obj.get_param('auth_signup.invitation_scope') == 'b2c'
        values['disable_footer'] = param_obj.get_param('disable_footer')
        style = param_obj.get_param('login_background.style')
        background = param_obj.get_param('login_background.background')
        values['background_color'] = param_obj.get_param('login_background.color')
        background_image = param_obj.get_param('login_background.background_image')

        if background == 'image':
            image_url = ''
            if background_image:
                base_url = param_obj.get_param('web.base.url')
                image_url = base_url + '/web/image?' + 'model=login.image&id=' + background_image + '&field=image'
                values['background_src'] = image_url or ''
                values['background_color'] = ''

        if background == 'color':
            values['background_src'] = ''

        if style == 'default' or style is False:
            response = request.render('web.login', values)
        elif style == 'left':
            response = request.render('yizuo_login_background_and_styles.left_login_template', values)
        elif style == 'right':
            response = request.render('yizuo_login_background_and_styles.right_login_template', values)
        else:
            response = request.render('yizuo_login_background_and_styles.middle_login_template', values)

        response.headers['X-Frame-Options'] = 'SAMEORIGIN'
        response.headers['Content-Security-Policy'] = "frame-ancestors 'self'"
        assert isinstance(response, object)
        return response
