/*
 * Copyright 2014 The Closure Compiler Authors.
 *
 * 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 com.google.javascript.jscomp.lint;

import com.google.javascript.jscomp.AbstractCompiler;
import com.google.javascript.jscomp.CompilerPass;
import com.google.javascript.jscomp.DiagnosticType;
import com.google.javascript.jscomp.NodeTraversal;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeUtil;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import java.util.HashSet;
import java.util.Set;

/**
 * Checks the following:
 *
 * <ol>
 *   <li>Whether there are duplicate values in enums.
 *   <li>Whether enum type (and its initializer values) are string/number or not.
 *   <li>Whether string enum values are statically initialized or not.
 * </ol>
 */
public final class CheckEnums extends AbstractPostOrderCallback implements CompilerPass {
  public static final DiagnosticType DUPLICATE_ENUM_VALUE = DiagnosticType.disabled(
      "JSC_DUPLICATE_ENUM_VALUE",
      "The value {0} is duplicated in this enum.");
  public static final DiagnosticType COMPUTED_PROP_NAME_IN_ENUM = DiagnosticType.disabled(
      "JSC_COMPUTED_PROP_NAME_IN_ENUM",
      "Computed property name used in enum.");
  public static final DiagnosticType SHORTHAND_ASSIGNMENT_IN_ENUM = DiagnosticType.disabled(
      "JSC_SHORTHAND_ASSIGNMENT_IN_ENUM",
      "Shorthand assignment used in enum.");
  public static final DiagnosticType ENUM_PROP_NOT_CONSTANT = DiagnosticType.disabled(
      "JSC_ENUM_PROP_NOT_CONSTANT",
      "enum key {0} must be in ALL_CAPS.");

  public static final DiagnosticType ENUM_TYPE_NOT_STRING_OR_NUMBER =
      DiagnosticType.disabled(
          "JSC_ENUM_VALUE_NOT_STRING_OR_NUMBER",
          "enum type must be either string or number."
          );

  public static final DiagnosticType NON_STATIC_INITIALIZER_STRING_VALUE_IN_ENUM =
      DiagnosticType.disabled(
          "JSC_NON_STATIC_INITIALIZER_STRING_VALUE_IN_ENUM",
          "enum string values must be statically initialized."

          );

  private final AbstractCompiler compiler;

  public CheckEnums(AbstractCompiler compiler) {
    this.compiler = compiler;
  }

  @Override
  public void process(Node externs, Node root) {
    NodeTraversal.traverse(compiler, root, this);
  }

  @Override
  public void visit(NodeTraversal t, Node n, Node parent) {
    if (n.isObjectLit()) {
      JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(n);
      if (jsdoc != null && jsdoc.hasEnumParameterType()) {
        checkNamingAndAssignmentUsage(t, n);
        checkDuplicateEnumValues(t, n);
        checkEnumTypeAndInitializerValues(t, n, jsdoc);
      }
    }
  }

  private static void checkEnumTypeAndInitializerValues(
      NodeTraversal t, Node n, JSDocInfo jsDocInfo) {
    JSTypeExpression enumTypeExpr = jsDocInfo.getEnumParameterType();

    Node enumType = enumTypeExpr.getRoot();
    boolean isStringEnum = enumType.isString() && enumType.getString().equals("string");
    boolean isNumberEnum = enumType.isString() && enumType.getString().equals("number");
    if (!isStringEnum && !isNumberEnum) {
      // warn on `@enum {?}`, `@enum {boolean}`, `@enum {Some|Another}`, `@enum {SomeName}` etc`
      t.report(n, ENUM_TYPE_NOT_STRING_OR_NUMBER);
    }
    if (isStringEnum) {
      checkStringEnumInitializerValues(t, n);
    }
  }

  // Reports a warning if the string enum value is not statically initialized
  private static void checkStringEnumInitializerValues(NodeTraversal t, Node enumNode) {
    for (Node prop : enumNode.children()) {
      // valueNode is guaranteed to exist by this time, as shorthand `{A}`s are converted to `{A:A}`
      Node valueNode = prop.getLastChild();
      if (!valueNode.isString() && !(valueNode.isTemplateLit() && valueNode.hasOneChild())) {
        // neither string nor substitution-free template literal
        t.report(valueNode, NON_STATIC_INITIALIZER_STRING_VALUE_IN_ENUM);
      }
    }
  }

  private void checkNamingAndAssignmentUsage(NodeTraversal t, Node objLit) {
    for (Node child : objLit.children()) {
      checkName(t, child);
    }
  }

  private void checkName(NodeTraversal t, Node prop) {
    if (prop.isComputedProp()) {
      t.report(prop, COMPUTED_PROP_NAME_IN_ENUM);
      return;
    }

    if (prop.isStringKey() && prop.isShorthandProperty()) {
      t.report(prop, SHORTHAND_ASSIGNMENT_IN_ENUM);
    }

    if (!compiler.getCodingConvention().isValidEnumKey(prop.getString())) {
      t.report(prop, ENUM_PROP_NOT_CONSTANT);
    }
  }

  private static void checkDuplicateEnumValues(NodeTraversal t, Node enumNode) {
    Set<String> values = new HashSet<>();
    for (Node prop : enumNode.children()) {
      Node valueNode = prop.getLastChild();
      String value;
      if (valueNode == null) {
        return;
      } else if (valueNode.isString()) {
        value = valueNode.getString();
      } else if (valueNode.isNumber()) {
        value = Double.toString(valueNode.getDouble());
      } else {
        return;
      }

      if (!values.add(value)) {
        t.report(valueNode, DUPLICATE_ENUM_VALUE, value);
      }
    }
  }
}

@@ -650,16 +650,83 @@
 .lint;%0A%0A
+import static com.google.common.base.Preconditions.checkArgument;%0A%0A
 import c
@@ -771,16 +771,16 @@
 mpiler;%0A
-
 import c
@@ -2740,17 +2740,21 @@
 lized.%22%0A
-%0A
+     
         
@@ -2750,25 +2750,73 @@
             
- 
++ %22 Consider using a const object without @enum.%22
 );%0A%0A  privat
@@ -3530,24 +3530,63 @@
 sDocInfo) %7B%0A
+    checkArgument(n.isObjectLit(), n);%0A
     JSTypeEx
@@ -4306,24 +4306,77 @@
 enumNode) %7B%0A
+    checkArgument(enumNode.isObjectLit(), enumNode);%0A
     for (Nod
@@ -4642,24 +4642,24 @@
 Child())) %7B%0A
-
         // n
@@ -4710,16 +4710,33 @@
  literal
+; report finding.
 %0A       

Add fix suggestion in the linter message for non-statically initialized string enums