/*****************************************************************
 *   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.cayenne.conf;

import java.io.PrintWriter;
import java.util.Iterator;

import org.apache.cayenne.conn.DataSourceInfo;
import org.apache.cayenne.project.Project;
import org.apache.cayenne.util.Util;

/**
 * Class that does saving of Cayenne configuration.
 * 
 * @author Andrei Adamchik
 */
public class ConfigSaver {
    protected ConfigSaverDelegate delegate;

    /**
     * Constructor for ConfigSaver.
     */
    public ConfigSaver() {
        super();
    }

    /**
       * Constructor for ConfigSaver.
       */
    public ConfigSaver(ConfigSaverDelegate delegate) {
        this.delegate = delegate;
    }

    /** 
     * Saves domains into the specified file. Assumes that the maps have already
     * been saved.
     */
    public void storeDomains(PrintWriter pw) {
        pw.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        pw.println("<domains project-version=\"" + delegate.projectVersion() + "\">");

        Iterator it = delegate.domainNames();
        while (it.hasNext()) {
            storeDomain(pw, (String) it.next());
        }

        Iterator views = delegate.viewNames();
        while (views.hasNext()) {
            storeDataView(pw, (String) views.next());
        }
        pw.println("</domains>");
    }

    protected void storeDataView(PrintWriter pw, String dataViewName) {
        String location = delegate.viewLocation(dataViewName);
        pw.print("<view name=\"" + dataViewName.trim());
        pw.print("\" location=\"" + location.trim());
        pw.println("\"/>");
    }

    protected void storeDomain(PrintWriter pw, String domainName) {
        pw.println("<domain name=\"" + domainName.trim() + "\">");

        // store properties
        Iterator properties = delegate.propertyNames(domainName);
        boolean breakNeeded = properties.hasNext();
        while (properties.hasNext()) {
            String name = (String) properties.next();
            if (name == null) {
                continue;
            }

            String value = delegate.propertyValue(domainName, name);
            if (value == null) {
                continue;
            }

            pw.print("\t<property name=\"" + Util.encodeXmlAttribute(name.trim()));
            pw.println("\" value=\"" + Util.encodeXmlAttribute(value.trim()) + "\"/>");
        }

        // store maps
        Iterator maps = delegate.mapNames(domainName);
        if (maps.hasNext()) {
            if (breakNeeded) {
                pw.println();
            }

            breakNeeded = true;
        }

        while (maps.hasNext()) {
            String mapName = (String) maps.next();
            String mapLocation = delegate.mapLocation(domainName, mapName);

            pw.print("\t<map name=\"" + mapName.trim());
            pw.print("\" location=\"" + mapLocation.trim());
            pw.println("\"/>");
        }

        // store nodes
        Iterator nodes = delegate.nodeNames(domainName);
        if (nodes.hasNext() && breakNeeded) {
            pw.println();
        }
        while (nodes.hasNext()) {
            String nodeName = (String) nodes.next();
            String datasource = delegate.nodeDataSourceName(domainName, nodeName);
            String adapter = delegate.nodeAdapterName(domainName, nodeName);
            String factory = delegate.nodeFactoryName(domainName, nodeName);
            Iterator mapNames = delegate.linkedMapNames(domainName, nodeName);

            pw.println("\t<node name=\"" + nodeName.trim() + "\"");

            if (datasource != null) {
                datasource = datasource.trim();
                pw.print("\t\t datasource=\"" + datasource + "\"");
            }
            pw.println("");

            if (adapter != null) {
                pw.println("\t\t adapter=\"" + adapter + "\"");
            }

            if (factory != null) {
                pw.print("\t\t factory=\"" + factory.trim() + "\"");
            }
            pw.println(">");

            while (mapNames.hasNext()) {
                String mapName = (String) mapNames.next();
                pw.println("\t\t\t<map-ref name=\"" + mapName.trim() + "\"/>");
            }
            pw.println("\t </node>");
        }
        pw.println("</domain>");
    }

    /**
     * Stores DataSolurceInfo to the specified PrintWriter.
     * <code>info</code> object may contain full or partial information.
     */
    public void storeDataNode(PrintWriter out, DataSourceInfo info) {
        out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        out.print("<driver project-version=\"" + Project.CURRENT_PROJECT_VERSION + "\"");
        if (info.getJdbcDriver() != null) {
            out.print(" class=\"" + info.getJdbcDriver() + "\"");
        }
        out.println(">");

        if (info.getDataSourceUrl() != null) {
            String encoded = Util.encodeXmlAttribute(info.getDataSourceUrl());
            out.println("\t<url value=\"" + encoded + "\"/>");
        }

        out.println(
            "\t<connectionPool min=\""
                + info.getMinConnections()
                + "\" max=\""
                + info.getMaxConnections()
                + "\" />");

        if (info.getUserName() != null || info.getPassword() != null) {
            out.print("\t<login");
            if (info.getUserName() != null) {
                String encoded = Util.encodeXmlAttribute(info.getUserName());
                out.print(" userName=\"" + encoded + "\"");
            }
            if (info.getPassword() != null) {
                String encoded = Util.encodeXmlAttribute(info.getPassword());
                out.print(" password=\"" + encoded + "\"");
            }
            out.println("/>");
        }

        out.println("</driver>");
    }
}
