/*
 * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0, which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the
 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
 * version 2 with the GNU Classpath Exception, which is available at
 * https://www.gnu.org/software/classpath/license.html.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
 */

package org.glassfish.jersey.server.wadl.internal.generators;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import javax.inject.Provider;
import javax.xml.parsers.SAXParserFactory;

import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.wadl.WadlGenerator;
import org.glassfish.jersey.server.wadl.internal.ApplicationDescription;
import org.glassfish.jersey.server.wadl.internal.WadlUtils;

import com.sun.research.ws.wadl.Application;
import com.sun.research.ws.wadl.Grammars;
import com.sun.research.ws.wadl.Method;
import com.sun.research.ws.wadl.Param;
import com.sun.research.ws.wadl.Representation;
import com.sun.research.ws.wadl.Request;
import com.sun.research.ws.wadl.Resource;
import com.sun.research.ws.wadl.Resources;
import com.sun.research.ws.wadl.Response;

/**
 * This {@link org.glassfish.jersey.server.wadl.WadlGenerator} adds the provided {@link Grammars} element to the
 * generated wadl-file.
 * <p>
 * The {@link Grammars} content can either be provided via a {@link File} ({@link #setGrammarsFile(File)}) reference or
 * via an {@link InputStream} ({@link #setGrammarsStream(InputStream)}).
 * </p>
 * <p>
 * The {@link File} should be used when using the maven-wadl-plugin for generating wadl offline,
 * the {@link InputStream} should be used when the extended wadl is generated by jersey at runtime, e.g.
 * using the {@link org.glassfish.jersey.server.wadl.config.WadlGeneratorConfig} for configuration.
 * </p>
 * Created on: Jun 24, 2008<br>
 *
 * @author Martin Grotzke (martin.grotzke at freiheit.com)
 */
public class WadlGeneratorGrammarsSupport implements WadlGenerator {

    private static final Logger LOG = Logger.getLogger(WadlGeneratorGrammarsSupport.class.getName());

    private WadlGenerator _delegate;
    private File _grammarsFile;
    private InputStream _grammarsStream;
    private Grammars _grammars;
    private Boolean overrideGrammars = false;

    @Context
    private Provider<SAXParserFactory> saxFactoryProvider;


    public WadlGeneratorGrammarsSupport() {
    }

    public WadlGeneratorGrammarsSupport(WadlGenerator delegate,
                                        Grammars grammars) {
        _delegate = delegate;
        _grammars = grammars;
    }

    public void setWadlGeneratorDelegate(WadlGenerator delegate) {
        _delegate = delegate;
    }

    public void setOverrideGrammars(Boolean overrideGrammars) {
        this.overrideGrammars = overrideGrammars;
    }

    public String getRequiredJaxbContextPath() {
        return _delegate.getRequiredJaxbContextPath();
    }

    public void setGrammarsFile(File grammarsFile) {
        if (_grammarsStream != null) {
            throw new IllegalStateException("The grammarsStream property is already set,"
                    + " therefore you cannot set the grammarsFile property. Only one of both can be set at a time.");
        }
        _grammarsFile = grammarsFile;
    }

    public void setGrammarsStream(InputStream grammarsStream) {
        if (_grammarsFile != null) {
            throw new IllegalStateException("The grammarsFile property is already set,"
                    + " therefore you cannot set the grammarsStream property. Only one of both can be set at a time.");
        }
        _grammarsStream = grammarsStream;
    }

    public void init() throws Exception {
        if (_grammarsFile == null && _grammarsStream == null) {
            throw new IllegalStateException("Neither the grammarsFile nor the grammarsStream"
                    + " is set, one of both is required.");
        }
        _delegate.init();
        _grammars = WadlUtils.unmarshall(_grammarsFile != null ? new FileInputStream(_grammarsFile) : _grammarsStream,
                saxFactoryProvider.get(), Grammars.class);
    }

    /**
     * @return application
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createApplication()
     */
    public Application createApplication() {
        final Application result = _delegate.createApplication();
        if (result.getGrammars() != null && !overrideGrammars) {
            LOG.info("The wadl application created by the delegate (" + _delegate + ") already contains a grammars element,"
                    + " we're adding elements of the provided grammars file.");
            if (!_grammars.getAny().isEmpty()) {
                result.getGrammars().getAny().addAll(_grammars.getAny());
            }
            if (!_grammars.getDoc().isEmpty()) {
                result.getGrammars().getDoc().addAll(_grammars.getDoc());
            }
            if (!_grammars.getInclude().isEmpty()) {
                result.getGrammars().getInclude().addAll(_grammars.getInclude());
            }
        } else {
            result.setGrammars(_grammars);
        }
        return result;
    }

    /**
     * @param ar  abstract resource
     * @param arm abstract resource method
     * @return method
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createMethod(org.glassfish.jersey.server.model.Resource,
     * org.glassfish.jersey.server.model.ResourceMethod)
     */
    public Method createMethod(org.glassfish.jersey.server.model.Resource ar,
                               org.glassfish.jersey.server.model.ResourceMethod arm) {
        return _delegate.createMethod(ar, arm);
    }

    /**
     * @param ar  abstract resource
     * @param arm abstract resource method
     * @return request
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createRequest(org.glassfish.jersey.server.model.Resource,
     * org.glassfish.jersey.server.model.ResourceMethod)
     */
    public Request createRequest(org.glassfish.jersey.server.model.Resource ar,
                                 org.glassfish.jersey.server.model.ResourceMethod arm) {
        return _delegate.createRequest(ar, arm);
    }

    /**
     * @param ar abstract resource
     * @param am abstract method
     * @param p  parameter
     * @return parameter
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createParam(org.glassfish.jersey.server.model.Resource,
     * org.glassfish.jersey.server.model.ResourceMethod, org.glassfish.jersey.server.model.Parameter)
     */
    public Param createParam(org.glassfish.jersey.server.model.Resource ar,
                             org.glassfish.jersey.server.model.ResourceMethod am, Parameter p) {
        return _delegate.createParam(ar, am, p);
    }

    /**
     * @param ar  abstract resource
     * @param arm abstract resource method
     * @param mt  media type
     * @return respresentation type
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createRequestRepresentation(org.glassfish.jersey.server.model.Resource,
     * org.glassfish.jersey.server.model.ResourceMethod, javax.ws.rs.core.MediaType)
     */
    public Representation createRequestRepresentation(
            org.glassfish.jersey.server.model.Resource ar, org.glassfish.jersey.server.model.ResourceMethod arm, MediaType mt) {
        return _delegate.createRequestRepresentation(ar, arm, mt);
    }

    /**
     * @param ar   abstract resource
     * @param path resource path
     * @return resource
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createResource(org.glassfish.jersey.server.model.Resource, String)
     */
    public Resource createResource(org.glassfish.jersey.server.model.Resource ar, String path) {
        return _delegate.createResource(ar, path);
    }

    /**
     * @return resources
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createResources()
     */
    public Resources createResources() {
        return _delegate.createResources();
    }

    /**
     * @param ar  abstract resource
     * @param arm abstract resource method
     * @return response
     * @see org.glassfish.jersey.server.wadl.WadlGenerator#createResponses(org.glassfish.jersey.server.model.Resource,
     * org.glassfish.jersey.server.model.ResourceMethod)
     */
    public List<Response> createResponses(org.glassfish.jersey.server.model.Resource ar,
                                          org.glassfish.jersey.server.model.ResourceMethod arm) {
        return _delegate.createResponses(ar, arm);
    }

    // ================ methods for post build actions =======================

    @Override
    public ExternalGrammarDefinition createExternalGrammar() {
        if (overrideGrammars) {
            return new ExternalGrammarDefinition();
        }
        return _delegate.createExternalGrammar();
    }

    @Override
    public void attachTypes(ApplicationDescription egd) {
        _delegate.attachTypes(egd);
    }

}
