/*
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 *
 * The Original Code is Protege-2000.
 *
 * The Initial Developer of the Original Code is Stanford University. Portions
 * created by Stanford University are Copyright (C) 2007.  All Rights Reserved.
 *
 * Protege was developed by Stanford Medical Informatics
 * (http://www.smi.stanford.edu) at the Stanford University School of Medicine
 * with support from the National Library of Medicine, the National Science
 * Foundation, and the Defense Advanced Research Projects Agency.  Current
 * information about Protege can be obtained at http://protege.stanford.edu.
 *
 */

package edu.stanford.smi.protege.model;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;


/**
 
 */
public class FrameID implements Serializable, Localizable {
    private static final long serialVersionUID = -3804918126573053937L;
    private String name;
    private int hashCode;
    
    private static WeakHashMap<String, WeakReference<String>> identityMap = new WeakHashMap<String, WeakReference<String>>();

    public FrameID(String name) {
        this.name = name;
        if (name != null) {
            intern();
            hashCode = name.hashCode() + 42;
        }
        else {
        	hashCode = 0;
        }
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof FrameID)) {
            return false;
        }
        FrameID other = (FrameID) o;
        return name == other.name;
    }

    @Override
    public final int hashCode() {
        return hashCode;
    }

    @Override
    public String toString() {
        return "FrameID(" + name + ")";
    }

    public void localize(KnowledgeBase kb) {
        if (name != null) {
            intern();
        }
    }
    

    private void intern() {
        synchronized (identityMap) {
            WeakReference<String> genericReference = identityMap.get(name);
            String genericName = null;
            if (genericReference != null && (genericName = genericReference.get()) != null) {
                name = genericName;
            }
            else {
                identityMap.put(name, new WeakReference<String>(name));
            }
        }
    }
}