/*
 * Copyright 2018, 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.type;

import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import io.spine.value.StringTypeValue;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.Deque;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newLinkedList;
import static java.util.stream.Collectors.joining;

/**
 * A value object holding a fully-qualified Java class name.
 *
 * @author Mikhail Mikhaylov
 */
public final class ClassName extends StringTypeValue {

    private ClassName(String value) {
        super(checkNotNull(value));
    }

    private ClassName(Class cls) {
        this(cls.getName());
    }

    /**
     * Creates a new instance with the name of the passed class.
     *
     * @param cls the class to get name from
     * @return new instance
     */
    public static ClassName of(Class cls) {
        return new ClassName(checkNotNull(cls));
    }

    /**
     * Creates a new instance with the passed class name value.
     *
     * @param className a fully-qualified Java class name
     * @return new
     */
    public static ClassName of(String className) {
        checkNotNull(className);
        checkArgument(className.length() > 0, "Class name cannot me empty");
        return new ClassName(className);
    }

    public static ClassName from(Descriptor descriptor) {
        return construct(descriptor.getName(),
                         descriptor.getFile(),
                         descriptor.getContainingType());
    }

    public static ClassName from(EnumDescriptor descriptor) {
        return construct(descriptor.getName(),
                         descriptor.getFile(),
                         descriptor.getContainingType());
    }

    private static ClassName construct(String typeName,
                                       FileDescriptor file,
                                       @Nullable Descriptor parent) {
        String packageName = javaPackageName(file);
        String parentTypes = parentClassPrefix(parent);
        String result = packageName + parentTypes + typeName;
        return of(result);
    }

    private static String javaPackageName(FileDescriptor file) {
        String javaPackage = file.getOptions()
                                 .getJavaPackage()
                                 .trim();
        String packageName = javaPackage.isEmpty()
                           ? file.getPackage()
                           : javaPackage;
        String result = packageName.isEmpty()
                      ? ""
                      : packageName + '.';
        return result;
    }

    private static String parentClassPrefix(@Nullable Descriptor parent) {
        if (parent == null) {
            return "";
        }
        Deque<String> parentClassNames = newLinkedList();
        Descriptor current = parent;
        while (current != null) {
            parentClassNames.addFirst(current.getName() + '$');
            current = current.getContainingType();
        }
        String result = parentClassNames.stream()
                                        .collect(joining());
        return result;
    }
}

@@ -1187,24 +1187,67 @@
 Descriptor;%0A
+import io.spine.code.java.SimpleClassName;%0A
 import io.sp
@@ -3218,24 +3218,76 @@
 Name(file);%0A
+        String outerClass = outerClassPrefix(file);%0A
         Stri
@@ -3367,16 +3367,29 @@
 geName +
+ outerClass +
  parentT
@@ -4461,11 +4461,437 @@
 t;%0A    %7D
+%0A%0A    private static String outerClassPrefix(FileDescriptor file) %7B%0A        boolean multipleFiles = file.getOptions()%0A                                    .getJavaMultipleFiles();%0A        if (multipleFiles) %7B%0A            return %22%22;%0A        %7D else %7B%0A            String className = SimpleClassName.outerOf(file.toProto())%0A                                              .value();%0A            return className + '$';%0A        %7D%0A    %7D
 %0A%7D%0A

Fix missing outer class prefix.