/*
 * Copyright (C) 2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * 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.
 *
 */
package com.arsdigita.search.lucene;

import com.arsdigita.domain.DomainObject;
import com.arsdigita.persistence.DataObject;
import com.arsdigita.persistence.OID;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.util.Assert;
import com.arsdigita.web.Host;
import com.arsdigita.web.Web;

import java.math.BigDecimal;

import org.apache.log4j.Logger;

/**
 * @author Vadim Nasardinov (vadimn@redhat.com)
 * @since 2004-01-07
 * @version $DateTime: 2004/04/07 16:07:11 $ $Revision: #3 $
 **/
class IndexId extends DomainObject {
    private final static Logger s_log = Logger.getLogger(IndexId.class);

    private static final String DATA_TYPE =
        "com.arsdigita.search.lucene.IndexId";
    private static final String INDEX_ID  = "indexID";
    private static final String HOST      = "host";

    private IndexId() {
        super(SessionManager.getSession().create(oid()));
        set(HOST, getHost());

        int id = (int) (Host.retrieveAll().size()-1);
        Assert.truth(id >= 0, "id greater than or equal to 0");
        Assert.truth(id <= 30, "id less than or equal to 30");

        set(INDEX_ID, new Integer(id));
    }

    private static OID oid() {
        return new OID(DATA_TYPE, getHost().getID());
    }

    private static Host getHost() {
        Host host = Host.retrieve(Web.getConfig().getHost());
        Assert.exists(host, Host.class);
        return host;
    }

    static Integer retrieveIndexID() {
        DataObject indexID =
            SessionManager.getSession().retrieve(oid());
        return indexID==null ? null : (Integer) indexID.get(INDEX_ID);
    }

    static class LoaderImpl implements Initializer.Loader {
        public void load() {
            if (IndexId.retrieveIndexID() == null ) {
                new IndexId().save();
            }
        }
    }
}
