/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/store/org/apache/slide/store/tamino/tools/collection/Collection.java,v 1.2 2004/04/14 11:56:02 juergen Exp $
 * $Revision: 1.2 $
 * $Date: 2004/04/14 11:56:02 $
 *
 * ====================================================================
 *
 * 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.tools.collection;

import com.softwareag.tamino.db.api.accessor.TAccessLocation;
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 com.softwareag.tamino.db.api.objectModel.TXMLObjectModel;
import com.softwareag.tamino.db.api.objectModel.jdom.TJDOMObjectModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.slide.util.Files;
import org.apache.slide.util.JDom;
import org.apache.slide.util.XException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class Collection {
    private static final String CONTENT = "content";
    private static final String SCHEMAS = "schemas";
    private static final String ENCODING = "UTF8";
    
    public static final TXMLObjectModel OBJECT_MODEL = TJDOMObjectModel.getInstance();
    
    private final TAccessLocation collection;
    private final TConnection connection;
    private final XMLOutputter outputter;
    private final SchemaAdapter schemas;
    private final ContentAdapter content;
    
    public Collection(String databaseUrl, String collectionName) throws TException {
        this.collection = TAccessLocation.newInstance(collectionName);
        this.connection = TConnectionFactory.getInstance().newConnection(databaseUrl);
        this.schemas = SchemaAdapter.create(connection, collection);
        this.content = ContentAdapter.create(connection, collection);
        this.outputter = new XMLOutputter();
    }
    
    public void save(File dir) throws TException, IOException {
        // TODO: check non-xml collection
        
        // save content first, because it checks if the collection exists
        System.out.println(doSave(new File(dir, CONTENT), content) + " document(s) saved");
        System.out.println(doSave(new File(dir, SCHEMAS), schemas) + " schema(s) saved");
    }
    
    private int doSave(File dir, Adapter adapter) throws TException, IOException {
        int i;
        ElementIterator iter;
        Element root;
        
        Files.mkdir(dir);
        iter = adapter.iterate();
        for (i = 0; iter.hasNext(); i++) {
            root = iter.next();
            saveDocument(root, new File(dir, "" + i));
        }
        return i;
    }
    
    private void saveDocument(Element root, File file) throws IOException {
        OutputStream out;
        
        // TODO: encoding
        out = new FileOutputStream(file);
        outputter.output(root, out);
        out.close();
    }
    
    public void load(File dir) throws IOException, TException, XException {
        if (delete()) {
            System.out.println("deleted collection " + collection.getCollection());
        }

        // schemas first -- prerequisites for closed content
        System.out.println(doLoad(new File(dir, SCHEMAS), schemas) + " schema(s) loaded");
        System.out.println(doLoad(new File(dir, CONTENT), content) + " document(s) loaded");
    }
    
    private int doLoad(File dir, Adapter adapter) throws IOException, TException, XException {
        File[] files;
        int i;
        File file;
        Element root;
        
        files = dir.listFiles();
        if (files == null) {
            throw new IOException("not a directory: " + dir);
        }
        for (i = 0; i < files.length; i++) {
            file = files[i];
            if (file.isFile()) {
                root = loadDocument(file);
                System.out.println("define " + file);
                adapter.insert(root);
            } else {
                // ignore directories, e.g. "CVS"
            }
        }
        return i;
    }
    
    private Element loadDocument(File file) throws XException {
        Document doc;
        Element root;
        
        doc = JDom.forFile(file);
        root = doc.getRootElement();
        root.detach();
        return root;
    }
    
    //--
    

    /**
     * @return true indificates success; false is returned if the exception did not exist
     */
    public boolean delete() throws TException {
        try {
            schemas.deleteCollection();
            return true;
        } catch (TUndefineException e) {
            if (e.getCause() != null && e.getCause().getMessage().indexOf("INOXRE8811") != -1) {
                return false;
            } else {
                throw e;
            }
        }
    }
}


