/*-
 * ~~~~~~licensing~~~~~~
 * permission-component
 * ==========
 * 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.core.permission.component.operation;

import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
import ru.entaxy.esb.system.jpa.entity.System;

import javax.persistence.NoResultException;

public class CheckSystemAccess extends BaseOperation {

    @Override
    protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
        validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getSubjectId());
        exchange.getIn().setBody(checkSystemAccessProc(endpoint), Boolean.class);
    }

    protected boolean checkSystemAccessProc(PermissionEndpoint endpoint) {
        System system = getSystem(endpoint.getSubjectId());
        boolean result = false;
        if (system != null) {
            result = getPermissionService().existByAllParameters(endpoint.getObjectId(), PermissionConstants.TYPE_SYSTEM,
                    String.valueOf(system.getId()), PermissionConstants.TYPE_SYSTEM, endpoint.getAction());
        }
        return result;
    }

    protected System getSystem(String subject) {
        try {
            long systemId = Long.valueOf(subject);
            return getSystemService().get(systemId);
        } catch (Exception e) {
            /*keep silence*/
        }
        System system = null;
        try {
            system = getSystemService().getByName(subject);
            return system;
        } catch (NoResultException e) {
            /*keep silence*/
        }

        try {
            system = getSystemService().getByUuid(subject);
        } catch (NoResultException e) {
            /*keep silence*/
        }

        return system;
    }

}
