# Copyright (c) 2021 Wind River Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import importlib
import logging

from django.conf import settings
from django.core.cache import caches

LOG = logging.getLogger(__name__)


class SimultaneousSessionsMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        self.simultaneous_sessions = settings.SIMULTANEOUS_SESSIONS

    def __call__(self, request):
        self._process_request(request)
        response = self.get_response(request)
        return response

    def _process_request(self, request):
        cache = caches['default']
        cache_key = ('user_pk_{}_restrict').format(request.user.pk)
        cache_value = cache.get(cache_key)
        if cache_value and self.simultaneous_sessions == 'disconnect':
            if request.session.session_key != cache_value:
                LOG.info('The user %s is already logged in, '
                         'the last session will be disconnected.',
                         request.user.id)
                engine = importlib.import_module(settings.SESSION_ENGINE)
                session = engine.SessionStore(session_key=cache_value)
                session.delete()
                cache.set(cache_key, request.session.session_key,
                          settings.SESSION_TIMEOUT)
        else:
            cache.set(cache_key, request.session.session_key,
                      settings.SESSION_TIMEOUT)
