/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 org.apache.cxf.tools.wsdl2java.frontend.jaxws;

import java.io.IOException;
import java.io.Writer;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.cxf.common.i18n.Message;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.tools.common.FrontEndGenerator;
import org.apache.cxf.tools.common.ToolConstants;
import org.apache.cxf.tools.common.ToolContext;
import org.apache.cxf.tools.common.ToolException;
import org.apache.cxf.tools.util.ClassCollector;
import org.apache.cxf.tools.util.FileWriterUtil;
import org.apache.cxf.version.Version;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public abstract class AbstractGenerator implements FrontEndGenerator {

    public static final String TEMPLATE_BASE = "org/apache/cxf/tools/wsdl2java/frontend/jaxws/template";
    private static final Logger LOG = LogUtils.getL7dLogger(AbstractGenerator.class);
    protected ToolContext env;
    //protected JavaModel javaModel;
    protected Map<String, Object> attributes = new HashMap<String, Object>();
    protected String name;
    //protected ClassCollector collector;

    public AbstractGenerator() {
    }

    public abstract boolean passthrough();

    public abstract void generate(ToolContext penv) throws ToolException;

    protected void doWrite(String templateName, Writer outputs) throws ToolException {
        Template tmpl = null;
        try {
            tmpl = Velocity.getTemplate(templateName);
        } catch (Exception e) {
            Message msg = new Message("TEMPLATE_MISSING", LOG, templateName);
            throw new ToolException(msg, e);
        }

        VelocityContext ctx = new VelocityContext();

        for (Iterator iter = attributes.keySet().iterator(); iter.hasNext();) {
            String key = (String)iter.next();
            ctx.put(key, attributes.get(key));
        }

        VelocityWriter writer = new VelocityWriter(outputs);
        try {
            tmpl.merge(ctx, writer);
            writer.close();
        } catch (Exception e) {
            Message msg = new Message("VELOCITY_ENGINE_WRITE_ERRORS", LOG);
            throw new ToolException(msg, e);
        }
    }

    protected boolean isCollision(String packageName, String filename) throws ToolException {        
        return isCollision(packageName, filename, ".java");
    }

    protected boolean isCollision(String packageName, String filename, String ext) throws ToolException {
        if (env.optionSet(ToolConstants.CFG_GEN_OVERWRITE)) {
            return false;
        }
        FileWriterUtil fw = new FileWriterUtil((String)env.get(ToolConstants.CFG_OUTPUTDIR));
        return fw.isCollision(packageName, filename + ext);
    }

    protected Writer parseOutputName(String packageName, String filename, String ext) throws ToolException {
        FileWriterUtil fw = null;
        Writer writer = null;

        fw = new FileWriterUtil((String)env.get(ToolConstants.CFG_OUTPUTDIR));
        try {
            writer = fw.getWriter(packageName, filename + ext);
        } catch (IOException ioe) {
            Message msg = new Message("FAIL_TO_WRITE_FILE", LOG, packageName + "." + filename + ext);
            throw new ToolException(msg, ioe);
        }

        return writer;
    }

    protected Writer parseOutputName(String packageName, String filename) throws ToolException {
        ClassCollector collector = (ClassCollector)env.get(ToolConstants.GENERATED_CLASS_COLLECTOR);
        
        if (ToolConstants.SEI_GENERATOR.equals(name)) {
            collector.addSeiClassName(packageName , filename , packageName + "." + filename);
        }
        
        if (ToolConstants.CLT_GENERATOR.equals(name)) {
            collector.addClientClassName(packageName , filename , packageName + "." + filename);
        }

        if (ToolConstants.FAULT_GENERATOR.equals(name)) {
            collector.addExceptionClassName(packageName , filename , packageName + "." + filename);
        }
        if (ToolConstants.SERVICE_GENERATOR.equals(name)) {
            collector.addServiceClassName(packageName , filename , packageName + "." + filename);
        }
        if (ToolConstants.SVR_GENERATOR.equals(name)) {
            collector.addServiceClassName(packageName , filename , packageName + "." + filename);

        }


        return parseOutputName(packageName, filename, ".java");
    }

    protected void setAttributes(String n, Object value) {
        attributes.put(n, value);
    }

    protected void setCommonAttributes() {
        attributes.put("currentdate", Calendar.getInstance().getTime());
        attributes.put("version", Version.getCurrentVersion());
    }

    protected void clearAttributes() {
        attributes.clear();
    }

    public void setEnvironment(ToolContext penv) {
        this.env = penv;

    }

    public ToolContext getEnvironment() {
        return this.env;
    }

    public String getName() {
        return this.name;
    }
}
