/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.i18n;

import java.io.IOException;
import java.io.Writer;
import java.util.ResourceBundle;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;

import com.google.common.base.CaseFormat;

/**
 * Processes Java source looking for {@link Message} annotations on problems and writes out their values to the default
 * `problems.properties` file.  We do it like this, because:
 *
 *  - We can keep default translations in-line, which is always nice.
 *  - We can keep a single mechanism for looking up messages, i.e. look in the {@link ResourceBundle}.
 *  - We can keep a single mechanism for dumping out i18n files for translators to use for new translations
 *  - We can avoid cluttering up the runtime with annotations and build the translation files on compile (not exactly
 *  scientifically proven to be better, but reflection is usually quite expensive)
 *
 */
@SupportedAnnotationTypes("nz.org.riskscape.engine.i18n.Message")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class TranslationProcessor extends AbstractProcessor {

  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    for (TypeElement anno : annotations) {
      if (!anno.getQualifiedName().toString().equals(Message.class.getCanonicalName())) {
        continue;
      }
      FileObject resource;
      Writer writer;
      try {
        resource =
            processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "i18n", "problems.properties");
        writer = resource.openWriter();

        processingEnv.getMessager().printMessage(Kind.NOTE, "Writing i18n to " + resource.getName());
      } catch (IOException e) {
        processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage());
        return true;
      }

      try {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(anno);
        for (Element element : elements) {
          if (element instanceof ExecutableElement) {
            Message message = element.getAnnotation(Message.class);

            if (!(element.getEnclosingElement() instanceof TypeElement)) {
              processingEnv.getMessager()
                .printMessage(Kind.ERROR, "Enclosing element is not a class or interface!", element);
              continue;
            }

            TypeElement classElement = (TypeElement) element.getEnclosingElement();
            // the format we use is overly-verbose - we should really consider adding some tips to the problem proxy
            // stuff to use a simpler format
            String className = classElement.getQualifiedName().toString();
            String methodName =
                CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, element.getSimpleName().toString());
            String messageValue = message.value();

            writer.write(className);
            writer.write(".");
            writer.write(methodName);
            writer.write(" = \\\n  ");
            writer.write(messageValue);
            writer.write("\n\n");
          }

        }

        writer.close();
      } catch (IOException e) {
        processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage());
      }
    }

    return true;
  }

}
