# -*- coding: utf-8 -*-
# © 2015-TODAY LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import operator

from openerp import http, _
from openerp.http import request
from openerp.addons.auth_signup.controllers.main import AuthSignupHome
from openerp.addons.web.controllers.main import ensure_db, Session

from ..exceptions import PassError



class PasswordSecurityHome(AuthSignupHome):


    @http.route()
    def web_login(self, *args, **kw):
        ensure_db()
        response = super(PasswordSecurityHome, self).web_login(*args, **kw)
        if not request.httprequest.method == 'POST':
            return response
        uid = request.session.authenticate(
            request.session.db,
            request.params['login'],
            request.params['password']
        )
        if not uid:
            return response
        users_obj = request.env['res.users'].sudo()
        user_id = users_obj.browse(request.uid)
        if not user_id._password_has_expired():
            return response
        user_id.action_expire_password()
        redirect = user_id.partner_id.signup_url
        return http.redirect_with_hash(redirect)

    @http.route('/web/signup', type='http', auth='public', website=True)
    def web_auth_signup(self, *args, **kw):
        try:
            return super(PasswordSecurityHome, self).web_auth_signup(
                *args, **kw
            )
        except PassError, e:
            qcontext = self.get_auth_signup_qcontext()
            qcontext['error'] = _(e.message)
            return request.render('auth_signup.signup', qcontext)

    @http.route(
        '/web/reset_password',
        type='http',
        auth='public',
        website=True
    )
    def web_auth_reset_password(self, *args, **kw):
        response = super(PasswordSecurityHome, self).web_auth_reset_password(
            *args,
            **kw
        )
        qcontext = response.qcontext
        if 'error' not in qcontext and qcontext.get('token'):
            qcontext['error'] = _("Sorry, your password has expired. Please reset your password.")
            return request.render('auth_signup.reset_password', qcontext)
        return response