/*-
 * ~~~~~~licensing~~~~~~
 * permission-impl
 * ==========
 * 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.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.Headers;
import org.osgi.framework.FrameworkUtil;
import ru.entaxy.esb.system.auth.basic.jpa.api.BasicAuthService;
import ru.entaxy.esb.system.auth.basic.jpa.api.entity.BasicAuthAccount;
import ru.entaxy.esb.system.common.osgi.OSGIUtils;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;

import javax.ws.rs.ForbiddenException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class ServiceInterceptor extends AbstractPhaseInterceptor<Message> {

    private static final Log LOG = LogFactory.getLog(ServiceInterceptor.class);
    private static final String APACHE_CXF_MESSAGE_MESSAGE_PATH_INFO = "org.apache.cxf.message.Message.PATH_INFO";
    private static final String HEADER_USER_LOGIN = "X-ForwardedUser";
    private static final String CXF = "/cxf/";

    private PermissionService permissionService;
    private BasicAuthService basicAuthService;

    public ServiceInterceptor() {
        super(Phase.RECEIVE);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        Map<String, List<String>> headers = Headers.getSetProtocolHeaders(message);
        String serviceName = message.get(APACHE_CXF_MESSAGE_MESSAGE_PATH_INFO).toString();
        if (serviceName.contains(CXF)) {
            serviceName = serviceName.replace(CXF, "");
        } else {
            int firstSlashIndex = serviceName.indexOf("/") + 1;
            serviceName = serviceName.substring(firstSlashIndex, serviceName.indexOf("/", firstSlashIndex));
        }

        Optional<String> login = Optional.ofNullable(headers.get(HEADER_USER_LOGIN))
                .orElse(Collections.emptyList())
                .stream().findFirst();

        Optional<BasicAuthAccount> basicAuthAccount = Optional.empty();
        if (login.isPresent()) {
            basicAuthAccount = getBasicAuthService().get(login.get());
        }

        LOG.trace(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>ServiceInterceptor" +
                " <<< serviceName " + serviceName +
                " <<< login " + login);
        if (!login.isPresent() || !basicAuthAccount.isPresent() ||
                !getPermissionService().existByAllParameters(basicAuthAccount.get().getId(), PermissionConstants.TYPE_ACCOUNT,
                        serviceName, PermissionConstants.TYPE_SERVICE, null)) {
            throw new ForbiddenException();
        }
    }

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

    public PermissionService getPermissionService() {
        if (permissionService == null) {
            permissionService = (PermissionService) OSGIUtils.getServiceReference(
                    FrameworkUtil.getBundle(ServiceInterceptor.class).getBundleContext(),
                    PermissionService.class.getName());
        }
        return permissionService;
    }

    public void setBasicAuthService(BasicAuthService basicAuthService) {
        this.basicAuthService = basicAuthService;
    }

    public BasicAuthService getBasicAuthService() {
        if (basicAuthService == null) {
            basicAuthService = (BasicAuthService) OSGIUtils.getServiceReference(
                    FrameworkUtil.getBundle(ServiceInterceptor.class).getBundleContext(),
                    BasicAuthService.class.getName());
        }
        return basicAuthService;
    }

}
