/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.validate;

import com.google.protobuf.DescriptorProtos.FieldOptions;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.GeneratedMessage.GeneratedExtension;
import io.spine.code.proto.FieldOption;

import java.util.Optional;

import static io.spine.validate.rule.ValidationRuleOptions.getOptionValue;
import static java.lang.String.format;

/**
 * An option that validates a field.
 *
 * <p>Validating options impose constraint on fields that they are applied to.
 *
 * @param <T>
 *         type of value held by this option
 * @param <F>
 *         type of field that this option is applied to
 */
abstract class FieldValidatingOption<T, F>
        extends FieldOption<T>
        implements ValidatingOption<T, FieldDescriptor, FieldValue<F>> {

    /** Specifies the extension that corresponds to this option. */
    protected FieldValidatingOption(GeneratedExtension<FieldOptions, T> optionExtension) {
        super(optionExtension);
    }

    /**
     * Returns an value of the option.
     *
     * @apiNote Should only be called by subclasses in circumstances that assume presence of
     *         the option. For all other cases refer to {@link this#valueFrom(FieldDescriptor)}.
     */
    T optionValue(FieldValue<F> value) throws IllegalStateException {
        FieldDescriptor field = value.declaration()
                                     .descriptor();
        Optional<T> option = valueFrom(field);
        return option.orElseThrow(() -> {
            FieldDescriptor descriptor = optionExtension().getDescriptor();

            String fieldName = value.declaration()
                                    .name()
                                    .value();
            String containingTypeName = descriptor.getContainingType()
                                                  .getName();
            return illegalState(fieldName, containingTypeName);
        });
    }

    private IllegalStateException illegalState(String fieldName, String containingTypeName) {
        String optionName = optionExtension().getDescriptor()
                                             .getName();
        String message = format("Could not get value of option %s from field %s in message %s.",
                                optionName,
                                fieldName,
                                containingTypeName);
        return new IllegalStateException(message);
    }

    /**
     * {@inheritDoc}
     *
     * <p>Apart from the value of the field option, checks whether any messages with {@code
     * validation_for} options exist that override the option value of the specified field.
     *
     * @param field
     *         a field that bears the option value
     * @return either an empty {@code Optional}, if no option value was found for the specified
     *         field,
     *         or an {@code Optional} containing found value
     */
    @Override
    public Optional<T> valueFrom(FieldDescriptor field) {
        FieldContext context = FieldContext.create(field);
        Optional<T> validationForOption = getOptionValue(context, optionExtension());
        return validationForOption.isPresent()
               ? validationForOption
               : super.valueFrom(field);
    }

    /**
     * Returns {@code true} if this option exists for the specified field, {@code false} otherwise.
     *
     * @param field
     *         the type of the field
     */
    boolean shouldValidate(FieldDescriptor field) {
        return valueFrom(field).isPresent();
    }
}

@@ -2423,24 +2423,72 @@
 scriptor();%0A
+        FieldContext context = value.context();%0A
         Opti
@@ -2509,30 +2509,53 @@
  = valueFrom
-(field
+Contextualized(field, context
 );%0A        r
@@ -3548,219 +3548,164 @@
   * 
-%7B@inheritDoc%7D%0A     *%0A     * %3Cp%3EApart from the value of the field option, checks whether any messages with %7B@code%0A     * validation_for%7D options exist that override the option value of the specified field.%0A     *
+Takes the value of the option from the given descriptor, given the specified context.%0A     *%0A     * @param descriptor%0A     *         descriptor of the field
 %0A   
@@ -3707,37 +3707,39 @@
 d%0A     * @param 
-field
+context
 %0A     *         
@@ -3742,74 +3742,46 @@
     
-a field that bears the option value%0A     * @return either an empty
+context of the field%0A     * @return an
  %7B@c
@@ -3797,15 +3797,16 @@
 nal%7D
-, if no
+ with an
  opt
@@ -3818,152 +3818,275 @@
 alue
- was found for the specified%0A     *         field,%0A     *         or an %7B@code Optional%7D containing found value%0A     */%0A    @Override%0A    public
+, if such exists, otherwise an empty%0A     *         %7B@code Optional%7D%0A     * @apiNote Use this in favour of %7B@link this#valueFrom(FieldDescriptor)%7D when%0A     *         %7B@code FieldContext%7D matters, e.g. when handling %7B@code validation_for%7D options.%0A     */%0A    private
  Opt
@@ -4095,32 +4095,46 @@
 nal%3CT%3E valueFrom
+Contextualized
 (FieldDescriptor
@@ -4134,32 +4134,27 @@
 criptor 
-field) %7B%0A       
+descriptor,
  FieldCo
@@ -4170,38 +4170,11 @@
 text
- = FieldContext.create(field);
+) %7B
 %0A   
@@ -4193,32 +4193,18 @@
 l%3CT%3E val
-idationForOption
+ue
  = getOp
@@ -4260,32 +4260,18 @@
 turn val
-idationForOption
+ue
 .isPrese
@@ -4299,24 +4299,10 @@
  val
-idationForOption
+ue
 %0A   
@@ -4319,14 +4319,8 @@
   : 
-super.
 valu
@@ -4325,21 +4325,26 @@
 lueFrom(
-field
+descriptor
 );%0A    %7D

Fix `validation_for` option value lookup.