/*-
 * ~~~~~~licensing~~~~~~
 * permission-manager
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * 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.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.management.permission.manager;

import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import ru.entaxy.esb.system.core.permission.jpa.entity.Permission;
import ru.entaxy.esb.system.jpa.SystemService;
import ru.entaxy.esb.system.jpa.entity.System;
import ru.entaxy.esb.system.management.permission.manager.dto.PermissionDto;
import ru.entaxy.esb.system.management.permission.manager.mapper.PermissionMapper;

import static ru.entaxy.esb.system.core.permission.common.PermissionConstants.TYPE_SYSTEM;

public class PermissionManagerImpl implements PermissionManager {

    private PermissionService permissionService;
    private SystemService systemService;
    private PermissionMapper permissionMapper;

    @Override
    public PermissionDto createPermission(PermissionDto permissionDto) {
        System object = systemService.getByUuid(permissionDto.getObjectId());
        System subject = systemService.getByUuid(permissionDto.getSubjectId());

        Permission permission = permissionService.addIfNotExist(object.getId(),
                TYPE_SYSTEM, String.valueOf(subject.getId()), TYPE_SYSTEM, null);
        return permissionMapper.toPermissionDto(permission);
    }

    @Override
    public void removePermission(PermissionDto permissionDto) {
        System object = systemService.getByUuid(permissionDto.getObjectId());
        System subject = systemService.getByUuid(permissionDto.getSubjectId());

        permissionService.remove(object.getId(), TYPE_SYSTEM, String.valueOf(subject.getId()),
                TYPE_SYSTEM, null);
    }

    @Override
    public void removeAllPermission(long id) {
        permissionService.removeAll(id, TYPE_SYSTEM);
    }

    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    public void setPermissionMapper(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    public void setSystemService(SystemService systemService) {
        this.systemService = systemService;
    }
}
