/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/testsuite/junit/store/org/apache/slide/store/tamino/Configuration.java,v 1.1 2004/03/25 16:18:13 juergen Exp $
 * $Revision: 1.1 $
 * $Date: 2004/03/25 16:18:13 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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 org.apache.slide.store.tamino;

import com.softwareag.tamino.db.api.accessor.TUndefineException;
import com.softwareag.tamino.db.api.common.TException;
import com.softwareag.tamino.db.api.connection.TConnection;
import com.softwareag.tamino.db.api.connection.TConnectionFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.slide.store.tamino.jdomobjects.XUuri;
import org.apache.slide.store.tamino.tools.Tws;
import org.apache.slide.store.tamino.tools.collection.Collection;
import org.apache.slide.store.tamino.tools.repairer.XTaminoClient;
import org.apache.slide.store.tamino.tools.stores.XDomainFileHandler;
import org.apache.slide.store.tamino.tools.stores.XNamespace;
import org.apache.slide.util.XAssertionFailed;
import org.apache.slide.util.XException;
import org.apache.slide.util.XUri;
import org.apache.slide.util.cli.Abort;
import org.apache.slide.util.os.Catalina;

/**
 * CAUTION: this configuration is not available for "unit" unit tests -- only for "large"
 * unit tests
 */
public class Configuration {
    public final String namespace;
    
    // always localhost - because
    public final String twsHost;
    public final int twsPort;
    public final String twsUser;
    public final String twsPassword;
    
    public final String taminoHost;
    public final String taminoDatabase;
    public final String taminoCollection;
    
    public final String datastoreDbsession;
    public final boolean datastoreAllowNonXml;
    public final boolean datastoreAutoCreateXmlSchema;
    
    public final Catalina catalina;
    
    private Configuration(
        String namespace, String taminoHost, String taminoDatabase, String taminoCollection,
        int twsPort, String twsUser, String twsPassword,
        String datastoreDbsession, boolean datastoreAllowNonXML, boolean datastoreAutoCreateXmlSchema)
        throws Abort {
        this.namespace = namespace;
        
        this.taminoHost = taminoHost;
        this.taminoDatabase = taminoDatabase;
        this.taminoCollection = taminoCollection;
        
        this.twsHost = "localhost"; // allways localhost - because we have to start/stop it
        this.twsPort = twsPort;
        this.twsUser = twsUser;
        this.twsPassword = twsPassword;
        
        this.datastoreDbsession = datastoreDbsession;
        this.datastoreAllowNonXml = datastoreAllowNonXML;
        this.datastoreAutoCreateXmlSchema = datastoreAutoCreateXmlSchema;
        this.catalina = Catalina.create();
    }
    
    public String getTwsUrl() {
        return HTTP + twsHost + ":" + twsPort + XUri.SEP + catalina.getContext();
    }
    
    public TConnection newConnection() throws TException {
        return TConnectionFactory.getInstance().newConnection (getTaminoDatabaseUrl());
    }
    
    public XTaminoClient newTaminoClient() throws TException, XException {
        return new XTaminoClient(newConnection(), taminoCollection);
    }
    
    /** @return never has a tailing / */
    public String getTaminoUrl() {
        return "http://" + taminoHost + "/tamino";
    }
    
    public String getTaminoDatabaseUrl() {
        return getTaminoUrl() + '/' + taminoDatabase;
    }
    
    public String toString() {
        // TODO: add missing fields
        return
            "**********************************************************\n" +
            "ENVIRONMENT\n" +
            "  tamino.host                   : " + taminoHost + "\n" +
            "  tamino.database               : " + taminoDatabase + "\n" +
            "  tamino.collection             : " + taminoCollection + "\n" +
            "  tws.host                      : " + twsHost + "\n" +
            "  tws.port                      : " + twsPort + "\n" +
            "  tws.user                      : " + twsUser + "\n" +
            "  tws.password                  : " + twsPassword + "\n" +
            "  datastore.dbsession           : " + datastoreDbsession + "\n" +
            "  datastore.allowNonXml         : " + datastoreAllowNonXml + "\n" +
            "  datastore.autoCreateXmlSchema : " + datastoreAutoCreateXmlSchema + "\n" +
            "**********************************************************";
    }
    
    
    //--
    
    private static final String HTTP = "http://";
    
    private static Configuration singleton = null;
    
    public static Configuration get() {
        Properties props;
        
        if (singleton == null) {
            props = load();
            try {
                singleton = new Configuration(
                    Tws.readNamespace(),
                    getString(props, "test.tamino.host"),
                    getString(props, "test.tamino.database"),
                    getString(props, "test.tamino.collection"),
                    
                    getInt(props, "test.tws.port"),
                    getString(props, "test.tws.user"),
                    getString(props, "test.tws.password"),
                    
                    getString(props, "test.datastore.dbsession"),
                    getBoolean(props, "test.datastore.allowNonXML"),
                    getBoolean(props, "test.datastore.autoCreateXmlSchema")
                );
                XUuri.initStoreScopes(singleton.namespace);
            } catch (Abort e)  {
                throw new XAssertionFailed(e);
            }
        }
        return singleton;
    }
    
    private static boolean getBoolean(Properties props, String key) {
        String bool;
        
        bool = getString(props, key);
        if ("true".equals(bool)) {
            return true;
        } else if ("false".equals(bool)) {
            return false;
        } else {
            throw new XAssertionFailed("property " + key + ": true or false expected: " + bool);
        }
    }
    
    private static int getInt(Properties props, String key) {
        String number;
        
        number = getString(props, key);
        try {
            return Integer.parseInt(number);
        } catch (NumberFormatException e) {
            throw new XAssertionFailed("property " + key + ": number expected: " + number);
        }
    }
    
    private static String getString(Properties props, String key) {
        String result;
        
        result = props.getProperty(key);
        if (result == null) {
            throw new XAssertionFailed("property not found: " + key);
        }
        return result;
    }
    
    public static Properties load() {
        Properties result;
        File file;
        
        file = getTestProperties();
        try {
            result = new Properties();
            result.load(new FileInputStream(file));
        } catch (IOException e) {
            throw new XAssertionFailed(e);
        }
        return result;
    }
    
    /** @return false if collection does not exist **/
    private boolean deleteCollection(String name) throws TException {
        try {
            return new Collection(getTaminoDatabaseUrl(), name).delete();
        } catch (TUndefineException e) {
            System.out.println("TODO: delete " + name + " failed");
            e.printStackTrace();
            return false;
        }
    }
    
    private static File getTestProperties() {
        String str;
        File file;
        
        str = System.getProperty("test.properties");
        if (str == null) {
            throw new XAssertionFailed("system property 'test.properties' not found");
        }
        file = new File(str);
        if (!file.isFile()) {
            throw new XAssertionFailed("test.properties not found: " + file);
        }
        return file;
    }
    
    //--
    
    public XNamespace getNamespace() {
        try {
            return XDomainFileHandler.get().getNamespace(namespace);
        } catch (XException e) {
            throw new XAssertionFailed(e);
        }
    }
}



