/*
* Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
*
* 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.
*/

package eu.teraflow.policy;

import eu.teraflow.policy.context.ContextService;
import eu.teraflow.policy.context.model.Device;
import eu.teraflow.policy.context.model.EndPointId;
import eu.teraflow.policy.context.model.Service;
import eu.teraflow.policy.context.model.ServiceId;
import io.smallrye.mutiny.Uni;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.jboss.logging.Logger;

@ApplicationScoped
public class PolicyRuleConditionValidator {

    private static final Logger LOGGER = Logger.getLogger(PolicyRuleConditionValidator.class);
    private static final String INVALID_MESSAGE = "%s is invalid.";
    private static final String VALID_MESSAGE = "%s is valid.";

    private final ContextService contextService;

    @Inject
    public PolicyRuleConditionValidator(ContextService contextService) {
        this.contextService = contextService;
    }

    public Uni<Boolean> validateDeviceId(String deviceId) {
        final var isDeviceIdValid = isDeviceIdValid(deviceId);

        isDeviceIdValid
                .subscribe()
                .with(
                        deviceIdIdBooleanValue -> {
                            if (Boolean.FALSE.equals(deviceIdIdBooleanValue)) {
                                LOGGER.errorf(INVALID_MESSAGE, deviceId);
                            }
                            LOGGER.infof(VALID_MESSAGE, deviceId);
                        });

        return isDeviceIdValid;
    }

    public Uni<Boolean> validateServiceId(ServiceId serviceId) {
        final var isServiceIdValid = isServiceIdValid(serviceId);

        isServiceIdValid
                .subscribe()
                .with(
                        serviceIdBooleanValue -> {
                            if (Boolean.FALSE.equals(serviceIdBooleanValue)) {
                                LOGGER.errorf(INVALID_MESSAGE, serviceId);
                            }
                        });

        return isServiceIdValid;
    }

    public Uni<Boolean> validateUpdatedPolicyRuleId(String updatedPolicyRuleId) {
        final var isUpdatedPolicyRuleIdValid = isUpdatedPolicyRuleIdValid(updatedPolicyRuleId);

        isUpdatedPolicyRuleIdValid
                .subscribe()
                .with(
                        serviceIdBooleanValue -> {
                            if (Boolean.FALSE.equals(serviceIdBooleanValue)) {
                                LOGGER.errorf(INVALID_MESSAGE, updatedPolicyRuleId);
                            }
                        });

        return isUpdatedPolicyRuleIdValid;
    }

    private Uni<Boolean> isDeviceIdValid(String deviceId) {
        return contextService
                .getDevice(deviceId)
                .onItem()
                .transform(device -> checkIfDeviceIdExists(device, deviceId));
    }

    private boolean checkIfDeviceIdExists(Device device, String deviceId) {
        final var deviceDeviceId = device.getDeviceId();

        return deviceDeviceId.equals(deviceId);
    }

    private Uni<Boolean> isServiceIdValid(ServiceId serviceId) {
        return contextService
                .getService(serviceId)
                .onItem()
                .transform(service -> checkIfServiceIdExists(service, serviceId));
    }

    private boolean checkIfServiceIdExists(Service service, ServiceId serviceId) {
        final var serviceServiceIdServiceId = service.getServiceId();
        final var serviceServiceIdContextId = serviceServiceIdServiceId.getContextId();
        final var serviceServiceIdId = serviceServiceIdServiceId.getId();

        return serviceServiceIdContextId.equals(serviceId.getContextId())
                && serviceServiceIdId.equals(serviceId.getId());
    }

    public Uni<Boolean> isServicesDeviceIdsValid(ServiceId serviceId, List<String> deviceIds) {
        return contextService
                .getService(serviceId)
                .onItem()
                .transform(service -> checkIfServicesDeviceIdsExist(service, deviceIds));
    }

    private boolean checkIfServicesDeviceIdsExist(Service service, List<String> deviceIds) {
        List<String> serviceDeviceIds = new ArrayList<>();
        for (EndPointId serviceEndPointId : service.getServiceEndPointIds()) {
            serviceDeviceIds.add(serviceEndPointId.getDeviceId());
        }

        return deviceIds.containsAll(serviceDeviceIds);
    }

    private Uni<Boolean> isUpdatedPolicyRuleIdValid(String updatedPolicyRuleId) {
        return contextService
                .getPolicyRule(updatedPolicyRuleId)
                .onItem()
                .ifNotNull()
                .transform(
                        id -> {
                            return true;
                        })
                .onItem()
                .ifNull()
                .continueWith(false);
    }
}
