# -*- coding: utf-8 -*-
# Part of Softhealer Technologies.
import logging
from odoo import api, models, SUPERUSER_ID
from odoo.exceptions import AccessDenied
from odoo.http import request
_logger = logging.getLogger(__name__)
import pytz

class LoginUser(models.Model):
    _inherit = 'res.users'

    @api.model
    def check_login_enabled(self, kw):
        user = self.env['res.users'].browse(kw)
        if user.user_has_groups('sh_login_as_other_user.sh_allow_login_as_other_user'):
            return True
        return False

    @classmethod
    def _login(cls, db, login, password):
        if not password:
            raise AccessDenied()
        ip = request.httprequest.environ['REMOTE_ADDR'] if request else 'n/a'
        try:
            with cls.pool.cursor() as cr:
                self = api.Environment(cr, SUPERUSER_ID, {})[cls._name]
                with self._assert_can_auth():
                    user = self.search(self._get_login_domain(login), order=self._get_login_order(), limit=1)
                    if not user:
                        raise AccessDenied()
                    user = user.sudo(user.id)
                    if type(request.params).__name__ == "OrderedDict":
                        user._check_credentials(password)
                        user._update_last_login()
                    else:
                        user._update_last_login()
        except AccessDenied:
            _logger.info("Login failed for db:%s login:%s from %s", db, login, ip)
            raise

        _logger.info("Login successful for db:%s login:%s from %s", db, login, ip)

        return user.id