/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/store/org/apache/slide/store/tamino/common/XThreadMap.java,v 1.1 2004/03/25 16:17:59 juergen Exp $
 * $Revision: 1.1 $
 * $Date: 2004/03/25 16:17:59 $
 *
 * ====================================================================
 *
 * 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.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.slide.store.tamino.jdomobjects.XTLock;
import org.apache.slide.util.XAssertionFailed;

public class XThreadMap {
    /** notified by remove if the map is empty **/
    private final Object notifyIfEmpty;

    /**
     ** The pool of delta caches. Mapping: Thread -> Object[] { List locks, XUriCache uriCache}
     ** Locks is a list of all TLock object where TLock.getType() != null (for the respective thread).
     ** Besides its use for comit/abort, this list is necessary for technical reasons to prevent locked
     ** objects from being garbage-collected.
     **/
    private final Map container;

    public XThreadMap( Object notifyIfEmpty ) {
        this.notifyIfEmpty = notifyIfEmpty;
        this.container = new HashMap();
    }

    public void clear() {
        container.clear();
    }
    
    public List getLocks() {
        return locks(get());
    }

    public XUriCache getUriCache() {
        return uriCache(get());
    }

    private static final Object[] EMPTY = new Object[] { null, null };

    /**
     * @return nevel null
     */
    private Object[] get() {
        Object[] result;

        result = lookup();
        if (result == null) {
            result = EMPTY;
        }
        return result;
    }

    /**
     ** @param lock
     ** @param uri  != null to add an uri
     **/
    public void add(XTLock lock, String uri) {
        Object[] pair;
        
        pair = lookup();
        if (pair == null) {
            pair = createPair();
            if (container.put(Thread.currentThread(), pair) != null) {
                throw new XAssertionFailed();
            }
        }
        locks(pair).add(lock);
        if (uri != null) {
            uriCache(pair).put(uri, lock.getUuri());
        }
    }
    
    /**
     * @return null if not found
     */
    private Object[] lookup() {
        return (Object[]) container.get(Thread.currentThread());
    }

    public void remove() {
        container.remove(Thread.currentThread());
        // Note that container.remove does nothing if the current thread has no delta cache.
        // This happens if a transaction is aborted before the thread has obtained a write lock.

        if (isEmpty()) {
            // notify all threads waiting on this object's monitor
            synchronized( notifyIfEmpty ) {
                notifyIfEmpty.notifyAll();
            }
        }
    }

    public String lookupUri(String uri) {
        XUriCache uriCache;
        uriCache = getUriCache();
        if (uriCache == null) {
            return null;
        }
        return uriCache.get(uri);
    }

    public boolean isEmpty() {
        return container.isEmpty();
    }

    /**
     * Get a report of locked resources
     */
    public String reportLockedResources() {
        StringBuffer sb;
        Iterator i;
        Map.Entry e;
        List locks;

        sb = new StringBuffer();
        i = container.entrySet().iterator();
        while( i.hasNext() ) {
            e = (Map.Entry) i.next();
            locks = locks((Object[]) e.getValue());
            sb.append("   Thread: "+e.getKey()+ " - Locked resources: "+locks+ "\n");
        }
        return sb.toString();
    }

    public boolean contains(XTLock lock) {
         Iterator i;
         Map.Entry e;
         List locks;
         
         i = container.entrySet().iterator();
         while (i.hasNext()) {
             e = (Map.Entry) i.next();
             locks = locks((Object[]) e.getValue());
             if (locks.contains(lock)) {
                 return true;
             }
         }
         return false;
    }

    /**
     * Checks that every lock in the thread map is a read or write lock and map in the DesciptorsCache.
     * @return number of locks
     */
    public void validate(XDescriptorsCache dc) {
         Iterator i;
         Map.Entry e;
         Thread current;
         List locks;
         Iterator j;
         XTLock lock;
         
         i = container.entrySet().iterator();
         while (i.hasNext()) {
             e = (Map.Entry) i.next();
             current = (Thread) e.getKey();
             locks = locks((Object[]) e.getValue());
             j = locks.iterator();
             while (j.hasNext()) {
                 lock = (XTLock) j.next();
                 if (lock.getType(current) == XTLock.NO_LOCK) {
                     throw new XAssertionFailed(current + ": " + lock.toString());
                 }
                 if (dc.lookup(lock.getUuri()) == null) {
                      throw new XAssertionFailed("not in Descriptors cache: " + lock.getUuri() + "\n" + dc);
                 }
             }
         }
    }

    //--

    private Object[] createPair() {
        return new Object[] { new ArrayList(), new XUriCache() };
    }

    private static List locks(Object[] pair) {
        return (List) pair[0];
    }

    private static XUriCache uriCache(Object[] pair) {
        return (XUriCache) pair[1];
    }
}
