/*
* Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
*
* 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 static org.assertj.core.api.Assertions.assertThat;

import context.ContextOuterClass;
import context.ContextOuterClass.Uuid;
import eu.teraflow.policy.monitoring.model.FloatKpiValue;
import eu.teraflow.policy.monitoring.model.IntegerKpiValue;
import io.quarkus.grpc.GrpcClient;
import io.quarkus.test.junit.QuarkusTest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
import monitoring.Monitoring.KpiId;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
import policy.Policy;
import policy.Policy.PolicyRuleBasic;
import policy.Policy.RuleState;
import policy.PolicyAction;
import policy.PolicyAction.PolicyRuleActionEnum;
import policy.PolicyCondition;
import policy.PolicyCondition.BooleanOperator;
import policy.PolicyCondition.NumericalOperator;
import policy.PolicyCondition.PolicyRuleCondition;
import policy.PolicyService;

@QuarkusTest
class PolicyServiceTest {
    private static final Logger LOGGER = Logger.getLogger(PolicyServiceTest.class);

    @GrpcClient PolicyService client;
    private final Serializer serializer;

    @Inject
    PolicyServiceTest(Serializer serializer) {
        this.serializer = serializer;
    }

    private PolicyRuleBasic createPolicyRuleBasic() {
        final var expectedPolicyRuleIdUuid =
                serializer.serializeUuid("571eabc1-0f59-48da-b608-c45876c3fa8a");

        final var expectedPolicyRuleId =
                Policy.PolicyRuleId.newBuilder().setUuid(expectedPolicyRuleIdUuid).build();

        final var expectedPolicyRuleState =
                Policy.PolicyRuleState.newBuilder().setPolicyRuleState(RuleState.POLICY_VALIDATED).build();

        final var expectedFirstKpiValue = new IntegerKpiValue(22);
        final var expectedSecondKpiValue = new FloatKpiValue(69.1f);

        final var serializedExpectedFirstKpiValue = serializer.serialize(expectedFirstKpiValue);
        final var serializedExpectedSecondKpiValue = serializer.serialize(expectedSecondKpiValue);

        final var firstExpectedPolicyRuleCondition =
                PolicyRuleCondition.newBuilder()
                        .setKpiId(
                                KpiId.newBuilder()
                                        .setKpiId(
                                                Uuid.newBuilder().setUuid("79e49ba3-a7b4-4b4b-8aaa-28b05c6f888e").build()))
                        .setNumericalOperator(NumericalOperator.POLICYRULE_CONDITION_NUMERICAL_EQUAL)
                        .setKpiValue(serializedExpectedFirstKpiValue)
                        .build();

        final var secondExpectedPolicyRuleCondition =
                PolicyCondition.PolicyRuleCondition.newBuilder()
                        .setKpiId(
                                KpiId.newBuilder()
                                        .setKpiId(
                                                Uuid.newBuilder().setUuid("eae900e5-2703-467d-82f2-97aae8b55c15").build()))
                        .setNumericalOperator(NumericalOperator.POLICYRULE_CONDITION_NUMERICAL_GREATER_THAN)
                        .setKpiValue(serializedExpectedSecondKpiValue)
                        .build();

        final var expectedPolicyRuleConditions =
                List.of(firstExpectedPolicyRuleCondition, secondExpectedPolicyRuleCondition);

        final var firstExpectedPolicyRuleAction =
                PolicyAction.PolicyRuleAction.newBuilder()
                        .setAction(PolicyAction.PolicyRuleActionEnum.POLICYRULE_ACTION_ADD_SERVICE_CONFIGRULE)
                        .addAllParameters(List.of("parameter1", "parameter2"))
                        .build();

        final var secondExpectedPolicyRuleAction =
                PolicyAction.PolicyRuleAction.newBuilder()
                        .setAction(PolicyRuleActionEnum.POLICYRULE_ACTION_ADD_SERVICE_CONSTRAINT)
                        .addAllParameters(List.of("parameter3", "parameter4"))
                        .build();

        final var expectedPolicyRuleActions =
                List.of(firstExpectedPolicyRuleAction, secondExpectedPolicyRuleAction);

        return PolicyRuleBasic.newBuilder()
                .setPolicyRuleId(expectedPolicyRuleId)
                .setPolicyRuleState(expectedPolicyRuleState)
                .addAllConditionList(expectedPolicyRuleConditions)
                .setBooleanOperator(BooleanOperator.POLICYRULE_CONDITION_BOOLEAN_OR)
                .addAllActionList(expectedPolicyRuleActions)
                .build();
    }

    @Test
    void shouldAddPolicyService() throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> message = new CompletableFuture<>();

        final var policyRuleBasic = createPolicyRuleBasic();

        final var expectedPolicyRuleState = policyRuleBasic.getPolicyRuleState();

        final var policyRuleService =
                Policy.PolicyRuleService.newBuilder().setPolicyRuleBasic(policyRuleBasic).build();

        client
                .policyAddService(policyRuleService)
                .subscribe()
                .with(policyRuleState -> message.complete(policyRuleState.getPolicyRuleState().toString()));

        assertThat(message.get(5, TimeUnit.SECONDS))
                .isEqualTo(expectedPolicyRuleState.getPolicyRuleState().toString());
    }

    @Test
    void shouldAddPolicyDevice() throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> message = new CompletableFuture<>();

        final var expectedDeviceIdUuid1 =
                serializer.serializeUuid("20db867c-772d-4872-9179-244ecafb3257");
        final var expectedDeviceIdUuid2 =
                serializer.serializeUuid("095974ac-d757-412d-b317-bcf355220aa9");

        final var expectedDeviceId1 =
                ContextOuterClass.DeviceId.newBuilder().setDeviceUuid(expectedDeviceIdUuid1).build();
        final var expectedDeviceId2 =
                ContextOuterClass.DeviceId.newBuilder().setDeviceUuid(expectedDeviceIdUuid2).build();

        final var policyRuleBasic = createPolicyRuleBasic();
        final var deviceIds = List.of(expectedDeviceId1, expectedDeviceId2);

        final var expectedPolicyRuleState = policyRuleBasic.getPolicyRuleState();

        final var policyRuleDevice =
                Policy.PolicyRuleDevice.newBuilder()
                        .setPolicyRuleBasic(policyRuleBasic)
                        .addAllDeviceList(deviceIds)
                        .build();

        client
                .policyAddDevice(policyRuleDevice)
                .subscribe()
                .with(policyRuleState -> message.complete(policyRuleState.getPolicyRuleState().toString()));

        assertThat(message.get(5, TimeUnit.SECONDS))
                .isEqualTo(expectedPolicyRuleState.getPolicyRuleState().toString());
    }

    @Test
    void shouldUpdatePolicyService()
            throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> message = new CompletableFuture<>();

        final var expectedPolicyRuleState =
                Policy.PolicyRuleState.newBuilder().setPolicyRuleState(RuleState.POLICY_ENFORCED).build();

        final var policyRuleBasic =
                PolicyRuleBasic.newBuilder().setPolicyRuleState(expectedPolicyRuleState).build();
        final var policyRuleService =
                Policy.PolicyRuleService.newBuilder().setPolicyRuleBasic(policyRuleBasic).build();

        client
                .policyUpdateService(policyRuleService)
                .subscribe()
                .with(policyRuleState -> message.complete(policyRuleState.getPolicyRuleState().toString()));

        assertThat(message.get(5, TimeUnit.SECONDS))
                .isEqualTo(expectedPolicyRuleState.getPolicyRuleState().toString());
    }

    @Test
    void shouldUpdatePolicyDevice()
            throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> message = new CompletableFuture<>();

        final var expectedPolicyRuleState =
                Policy.PolicyRuleState.newBuilder().setPolicyRuleState(RuleState.POLICY_ENFORCED).build();

        final var policyRuleBasic =
                PolicyRuleBasic.newBuilder().setPolicyRuleState(expectedPolicyRuleState).build();
        final var policyRuleDevice =
                Policy.PolicyRuleDevice.newBuilder().setPolicyRuleBasic(policyRuleBasic).build();

        client
                .policyUpdateDevice(policyRuleDevice)
                .subscribe()
                .with(policyRuleState -> message.complete(policyRuleState.getPolicyRuleState().toString()));

        assertThat(message.get(5, TimeUnit.SECONDS))
                .isEqualTo(expectedPolicyRuleState.getPolicyRuleState().toString());
    }

    @Test
    void shouldDeletePolicy() throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> message = new CompletableFuture<>();

        final var uuid =
                ContextOuterClass.Uuid.newBuilder()
                        .setUuid(UUID.fromString("0f14d0ab-9608-7862-a9e4-5ed26688389b").toString())
                        .build();
        final var policyRuleId = Policy.PolicyRuleId.newBuilder().setUuid(uuid).build();

        final var expectedPolicyRuleState =
                Policy.PolicyRuleState.newBuilder().setPolicyRuleState(RuleState.POLICY_REMOVED).build();

        client
                .policyDelete(policyRuleId)
                .subscribe()
                .with(policyRuleState -> message.complete(policyRuleState.getPolicyRuleState().toString()));

        assertThat(message.get(5, TimeUnit.SECONDS))
                .isEqualTo(expectedPolicyRuleState.getPolicyRuleState().toString());
    }

    @Test
    void shouldGetPolicyService() throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> message = new CompletableFuture<>();

        final var uuid =
                ContextOuterClass.Uuid.newBuilder()
                        .setUuid(UUID.fromString("0f14d0ab-9608-7862-a9e4-5ed26688389b").toString())
                        .build();
        final var policyRuleId = Policy.PolicyRuleId.newBuilder().setUuid(uuid).build();

        client
                .getPolicyService(policyRuleId)
                .subscribe()
                .with(
                        policyRuleService -> {
                            LOGGER.infof(
                                    "Getting policy with ID: %s",
                                    policyRuleService.getPolicyRuleBasic().getPolicyRuleId().getUuid());
                            message.complete(
                                    policyRuleService.getPolicyRuleBasic().getPolicyRuleId().getUuid().getUuid());
                        });

        assertThat(message.get(5, TimeUnit.SECONDS)).isEqualTo(policyRuleId.getUuid().getUuid());
    }

    @Test
    void shouldGetPolicyDevice() throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> message = new CompletableFuture<>();

        final var uuid =
                ContextOuterClass.Uuid.newBuilder()
                        .setUuid(UUID.fromString("0f14d0ab-9608-7862-a9e4-5ed26688389b").toString())
                        .build();
        final var policyRuleId = Policy.PolicyRuleId.newBuilder().setUuid(uuid).build();

        client
                .getPolicyDevice(policyRuleId)
                .subscribe()
                .with(
                        policyRuleService -> {
                            LOGGER.infof(
                                    "Getting policy with ID: %s",
                                    policyRuleService.getPolicyRuleBasic().getPolicyRuleId().getUuid());
                            message.complete(
                                    policyRuleService.getPolicyRuleBasic().getPolicyRuleId().getUuid().getUuid());
                        });

        assertThat(message.get(5, TimeUnit.SECONDS)).isEqualTo(policyRuleId.getUuid().getUuid());
    }

    @Test
    void shouldGetPolicyByServiceId()
            throws ExecutionException, InterruptedException, TimeoutException {

        CompletableFuture<String> message = new CompletableFuture<>();

        final var uuid =
                ContextOuterClass.Uuid.newBuilder()
                        .setUuid(UUID.fromString("0f14d0ab-9608-7862-a9e4-5ed26688389b").toString())
                        .build();
        final var serviceId = ContextOuterClass.ServiceId.newBuilder().setServiceUuid(uuid).build();

        client
                .getPolicyByServiceId(serviceId)
                .subscribe()
                .with(
                        policyRuleList -> {
                            LOGGER.infof("Getting policyRuleList with ID: %s", policyRuleList);
                            message.complete(policyRuleList.toString());
                        });

        assertThat(message.get(5, TimeUnit.SECONDS)).isEmpty();
    }
}
