/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/store/org/apache/slide/store/tamino/jdomobjects/XUuri.java,v 1.2 2004/12/15 10:38:27 pnever Exp $
 * $Revision: 1.2 $
 * $Date: 2004/12/15 10:38:27 $
 *
 * ====================================================================
 *
 * 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.jdomobjects;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.slide.store.tamino.tools.stores.XDomainFileHandler;
import org.apache.slide.store.tamino.tools.stores.XStore;
import org.apache.slide.store.tamino.tools.stores.XStoreGroup;
import org.apache.slide.store.tamino.tools.stores.XStoreType;
import org.apache.slide.util.XAssertionFailed;
import org.apache.slide.util.XException;
import org.apache.slide.util.XUri;
import org.apache.slide.webdav.util.BindConstants;

/**
 * Uri unique within a store. Note that there may be multiple XDescritor or ObjectNode clones with
 * the same uuri.  TODO: turn this into a true data type
 *
 * @version $Revision: 1.2 $
 */
public class XUuri {
    private static final String SCHEME = BindConstants.S_RESOURCE_ID;
    
    /**
     ** There are probably no two jvm's working on the same database that initialitzing this
     ** class at the same mill second
     **/
    private static final String PREFIX =  System.currentTimeMillis() + ".";
    
    /**
     ** Number of uuri created in this JVM session
     **/
    private static int counter = 0;
    
    /**
     * @pre  uriStr has to contain store prefix, i.e. extractStoreUri has to succeed
     */
    public static String create(boolean useBinding, String uriStr) {
        if (useBinding) {
            XUri uri;
            
            synchronized (XUuri.class) {
                uri = new XUri(uriStr);
                if (isStoreUri(uriStr)) {
                    return getStoreUuri(true, uri);
                } else {
                    return SCHEME+extractStoreUri(uri)+"/"+PREFIX+counter++;
                }
            }
        } else {
            return uriStr;
        }
    }
    
    public static boolean isUuri(String uuri) {
        return uuri.startsWith(SCHEME);
    }
    
    public static boolean isStoreUuri(String uuri) {
        if (isUuri(uuri)) {
            return uuri.startsWith(SCHEME) && uuri.endsWith("/");
        } else {
            return isStoreUri( uuri );
        }
    }
    
    /** technically, a List would be sufficient. But we use a HashMap because containment can be
        checked much faster. */
    private static Map storeScopes;
    
    public static Map getScopes() {
        return storeScopes;
    }
    
    public static void clearScopes() {
        storeScopes = null;
    }
    // TODO: ugly - turn UUri into an object instead
    public static void initStoreScopes(String namespace) {
        Iterator iter;
        XStoreGroup group;
        
        if (namespace == null) {
            throw new XAssertionFailed("missing namespace");
        }
        if (storeScopes != null) {
            throw new XAssertionFailed("scopes already initialized");
        }
        storeScopes = new HashMap();
        try {
            iter = XDomainFileHandler.get().getNamespace(namespace).getPublicStoreGroups().iterator();
        } catch (XException e) {
            throw new XAssertionFailed(e);
        }
        while (iter.hasNext()) {
            group = (XStoreGroup) iter.next();
            group.forAll(new XStoreGroup.Visitor() {
                        public void visit(XStoreType type, XStore store) {
                            XUri scope;
                            
                            scope = store.getScope();
                            storeScopes.put(scope.toString(), scope);
                        }
                    });
        }
    }
    
    public static boolean isStoreUri(String uri) {
        return storeScopes.containsKey(uri);
    }

    /**
     ** @return binding uuri
     **/
    public static String getStoreUuri(boolean useBinding, XUri uri) {
        if (useBinding) {
            return SCHEME+uri.toString()+"/"; // uri.toString() starts with "/"
        } else {
            return uri.toString();
        }
    }
    
    public static String getStoreUri(String uuri) {
        if (isStoreUuri(uuri)) {
            // TODO: correct if binding is disabled?
            return uuri.substring(SCHEME.length(), uuri.length() - 1);
        } else {
            throw new XAssertionFailed("Store UURI expected: " + uuri);
        }
    }
    
    public static XUri extractStoreUri(XUri uri) {
        int i;
        XUri prefix;
        
        for (i = uri.size(); i >= 1; i--) {
            prefix = uri.suburi(0, i);
            if (XUuri.isStoreUri(prefix.toString())) {
                return prefix;
            }
        }
        throw new XAssertionFailed(uri.toString());
    }
}



