/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * 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 com.queplix.core.modules.eql.utils.cache;

import com.queplix.core.jxb.entity.Efield;
import com.queplix.core.jxb.entity.Entity;
import com.queplix.core.modules.eql.EQLERes;
import com.queplix.core.modules.eql.EQLObject;
import com.queplix.core.modules.eql.EQLReqField;
import com.queplix.core.modules.eql.EQLRes;
import com.queplix.core.modules.eql.EQLResCell;
import com.queplix.core.modules.eql.EQLResRecord;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Entity EQL response cache object</p>
 *
 * @author Baranov Andrey [ALB]
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:33 $
 */

public class EQLResCacheObject
        implements java.io.Serializable {

    private String id;
    private long version;

    private EQLRes res;
    private Map index = Collections.synchronizedMap(new HashMap());

    /**
     * Constructor
     *
     * @param id      unique cache id
     * @param version cache version
     */
    public EQLResCacheObject(String id, long version) {

        if(id == null) {
            throw new NullPointerException("Cache ID is NULL");
        }

        this.id = id;
        this.version = version;
    }

    /**
     * Get cache version
     *
     * @return cache version
     */
    public long getVersion() {
        return version;
    }

    /**
     * Get EQL response object
     *
     * @return EQLRes object
     */
    public EQLRes getEQLRes() {
        if(res == null) {
            throw new IllegalStateException("Call setEQLRes first!");
        }
        return res;
    }

    /**
     * Get indexed EQLResCell object for <code>field</code>.
     *
     * @param entity EQL entity.
     * @param field  EQL field.
     * @param pkey   pkey value
     * @return indexed EQLResCell object
     */
    public EQLResCell getCell(Entity entity, Efield field, Object pkey) {
        CacheIndexMap cim = (CacheIndexMap) index.get(pkey);
        if(cim == null) {
            throw new IllegalStateException(
                    "Cannot find CacheIndexMap in cache '" + id +
                            "' for pkey: " + pkey + ". Class: " +
                            ((pkey == null) ? null:pkey.getClass().getName()));
        }
        return cim.getIndex(entity, field);
    }

    /**
     * Set EQL response object
     *
     * @param res EQL entity response object
     */
    public synchronized void setEQLRes(EQLERes res) {

        if(res == null) {
            throw new NullPointerException("EQL response is NULL");
        }
        this.res = res;

        // try to index EQLRes
        Entity baseEntity = res.getEntity();
        int records = res.size();

        if(records == 0) {
            throw new IllegalStateException(
                    "Cannot index empty result set in cache '" +
                            id + "'. Entity '" + baseEntity.getName() + "'.");
        }

        for(int i = 0; i < records; i++) {
            EQLResRecord record = res.getRecord(i);
            int cells = record.size();

            // get pkey value (pkey should be at the first position in the entity)
            EQLResCell pkeyCell = record.getResCell(0);
            Object pkey = pkeyCell.getEQLObject().getObject();

            // create new CacheIndexMap object
            CacheIndexMap cim = new CacheIndexMap();
            index.put(pkey, cim);

            // in cycle select all next cells
            for(int j = 1; j < cells; j++) {
                EQLResCell cell = record.getResCell(j);
                cim.addIndex(cell);
            }
        }
    }

    //
    // hash code
    //
    public int hashCode() {
        return (int) ((version >>> 32) ^ version) | id.hashCode();
    }

    //
    // equals
    //
    public boolean equals(Object o) {
        if(!(o instanceof EQLResCacheObject)) {
            return false;
        }

        EQLResCacheObject co = (EQLResCacheObject) o;
        return id.equals(co.id) && (version == co.version);
    }

    // ----------------------------------------------------- inner class

    /**
     * <p>Class for indexing</p>
     *
     * @author [ALB] Baranov Andrey
     * @version 1.0
     */
    static class CacheIndexMap {
        private Map indexMap = Collections.synchronizedMap(new HashMap());

        // Add index.
        void addIndex(EQLResCell cell) {
            indexMap.put(cell.getReqField().getField().getId(),
                    cell.getEQLObject());
        }

        // Get index.
        EQLResCell getIndex(Entity entity, Efield field) {
            EQLObject obj = (EQLObject) indexMap.get(field.getId());
            if(obj == null) {
                throw new IllegalStateException(
                        "Cannot find EQLObject for field '" +
                                field.getId() + "'.");
            }
            return new EQLResCell(new EQLReqField(entity, field), obj);
        }
    }

}
