"""Middleware for the API

for handling tenant requests
"""

from flask_security import current_user
from flask import session
from .database import Database
from .eveai_exceptions import EveAINoSessionTenant, EveAINoSessionPartner, EveAINoManagementPartnerService, \
    EveAINoManagementPartnerForTenant
from common.services.user import UserServices


def mw_before_request():
    """Before request

    switch tenant schema
    """

    if 'tenant' not in session:
        raise EveAINoSessionTenant()

    tenant_id = session['tenant']['id']
    if not tenant_id:
        raise EveAINoSessionTenant()

    switch_allowed = False
    if current_user.has_role('Super User'):
        switch_allowed = True
    if current_user.has_role('Tenant Admin') and current_user.tenant_id == tenant_id:
        switch_allowed = True
    if current_user.has_role('Partner Admin'):
        if 'partner' not in session:
            raise EveAINoSessionPartner()
        management_service = next((service for service in session['partner']['services']
                                   if service.get('type') == 'MANAGEMENT_SERVICE'), None)
        if not management_service:
            raise EveAINoManagementPartnerService()
        if not UserServices.can_user_edit_tenant(tenant_id):
            raise EveAINoManagementPartnerForTenant()

    Database(tenant_id).switch_schema()


