import logging
import json

from fastapi import APIRouter, Depends, HTTPException, Form

from intranet.library.fastapi_csrf.src import csrf_exempt

from intranet.trip.src.api.depends import get_unit_of_work, only_for_tvm
from intranet.trip.src.unit_of_work import UnitOfWork


logger = logging.getLogger(__name__)
router = APIRouter()


@router.get('/info/')
async def info(
    _auth=Depends(only_for_tvm('idm')),
):
    return {
        'code': 0,
        'roles': {
            'slug': 'role',
            'name': 'роль',
            'values': {
                'coordinator': {
                    'name': {
                        'ru': 'Координатор',
                        'en': 'Coordinator',
                    },
                },
                'limited_access': {
                    'name': {
                        'ru': 'Ограниченный доступ',
                        'en': 'Limited access',
                    },
                },
            },
        },
    }


@router.post('/add-role/')
@csrf_exempt
async def add_role(
    role: str = Form(...),
    login: str = Form(...),
    _auth=Depends(only_for_tvm('idm')),
    uow: UnitOfWork = Depends(get_unit_of_work()),
):
    role = json.loads(role)
    role_to_person_column = {
        'coordinator': 'is_coordinator',
        'limited_access': 'is_limited_access',
    }
    role_key = role.get('role')
    if role_key not in role_to_person_column:
        raise HTTPException(status_code=400, detail='Wrong role')
    modified_rows_count = await uow.persons.add_role(login, role_to_person_column[role_key])
    if not modified_rows_count:
        message = 'No person found with login "%s"'
        logger.warning(message, login)
        return {
            'code': 1,
            'error': message % login,
        }
    logger.info('Added role "%s" to "%s"', role_key, login)
    return {'code': 0}


@router.post('/remove-role/')
@csrf_exempt
async def remove_role(
    role: str = Form(...),
    login: str = Form(...),
    _auth=Depends(only_for_tvm('idm')),
    uow: UnitOfWork = Depends(get_unit_of_work()),
):
    role = json.loads(role)
    role_to_person_column = {
        'coordinator': 'is_coordinator',
        'limited_access': 'is_limited_access',
    }
    role_key = role.get('role')
    if role_key not in role_to_person_column:
        raise HTTPException(status_code=400, detail='Wrong role')
    modified_rows_count = await uow.persons.remove_role(login, role_to_person_column[role_key])
    if not modified_rows_count:
        message = 'No person found with login "%s"'
        logger.warning(message, login)
        return {
            'code': 1,
            'error': message % login,
        }
    logger.info('Removed role "%s" to "%s"', role_key, login)
    return {'code': 0}


@router.get('/get-all-roles/')
async def get_all_roles(
    _auth=Depends(only_for_tvm('idm')),
    uow: UnitOfWork = Depends(get_unit_of_work(read_only=True)),
):
    roles_data = await uow.persons.get_roles()
    return {
        'code': 0,
        'users': [
            {
                'login': login,
                'roles': [
                    {'role': role_key}
                    for role_key, is_active in roles_config.items()
                    if is_active
                ],
            }
            for login, roles_config in roles_data.items()
        ],
    }
