/*-
 * ~~~~~~licensing~~~~~~
 * basic-auth-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.auth.basic.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 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.util.SystemHeadersConstants;
import ru.entaxy.esb.system.jpa.SystemService;
import ru.entaxy.esb.system.jpa.entity.System;

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

public class SystemInterceptor extends AbstractPhaseInterceptor<Message> {

    private static final Log LOG = LogFactory.getLog(SystemInterceptor.class);

    private BasicAuthService basicAuthService;

    private SystemService systemService;

    public SystemInterceptor() {
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        Map<String, List<String>> headers = Headers.getSetProtocolHeaders(message);

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

        //TEST
//		login = Optional.of("user");

        LOG.trace(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>SystemInterceptor <<<  headers.get( HEADER_USER_LOGIN ) " + login.orElse("NULL"));

        if (login.isPresent()) {
            Optional<BasicAuthAccount> accountOpt = basicAuthService.get(login.get());

            if (accountOpt.isPresent()) {
                BasicAuthAccount account = accountOpt.get();
                headers.put(SystemHeadersConstants.HEADER_USER_ID, Collections.singletonList(String.valueOf(account.getId())));

                headers.put(SystemHeadersConstants.HEADER_SYSTEM_UUID, Collections.singletonList(account.getSystemUUID()));

                System system = account.getSystemUUID() != null && !account.getSystemUUID().isEmpty()
                        ? systemService.getByUuid(account.getSystemUUID())
                        : null;
                if (system != null) {
                    headers.put(SystemHeadersConstants.HEADER_SYSTEM_NAME, Collections.singletonList(system.getName()));
                    headers.put(SystemHeadersConstants.HEADER_SYSTEM_ID, Collections.singletonList(String.valueOf(system.getId())));
                }
            } else {
                throw new ForbiddenException();
            }
        }

//        It stops the process
//        else {
//             message.getInterceptorChain().abort();
//        }

    }

    public BasicAuthService getBasicAuthService() {
        return basicAuthService;
    }

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

    public SystemService getSystemService() {
        return systemService;
    }

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

}
