/*
 * 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.client.frames.mainframe.impl;

import com.queplix.core.client.app.vo.EntityData;
import com.queplix.core.client.app.vo.FieldData;
import com.queplix.core.client.app.vo.GridData;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Class incapsulate logic of working with register of forms data.
 *
 * @author Sergey Kozmin
 * @since 24.11.2006, 16:18:20
 */
class FormsDataRegistry {
    /**
     * Map &lt;String, EntityData&gt;
     */
    private Map fullEntitiesData = new HashMap();
    /**
     * Contains information, was this data consumed by form or not.
     * Map<String, Set<String>>
     */
    private Map dataConsumedByForm = new HashMap();
    /**
     * this field contains entity names for those entities, that came as external fields.
     */
    private Collection externalFieldsEntities = new HashSet();
    /**
     * Map<String, GridData>. Contains grid info for forms to be filled.
     */
    private Map gridDataMap = new HashMap();
    /**
     * Contains information about data consumption by grid
     */
    private Map dataConsumedByGrid = new HashMap();
    
    private void addFieldsToMap(Map fieldsMap, FieldData[] fields) {
        for (int i = 0; i < fields.length; i++) {
            String fieldId = fields[i].getFieldID();
            fieldsMap.put(fieldId, fields[i]);
        }
    }
    
    private FieldData[] collectFields(Map fieldsMap) {
        FieldData[] result = new FieldData[fieldsMap.size()];
        int i = 0;
        for (Iterator it = fieldsMap.values().iterator(); it.hasNext(); ) {
            result[i++] = (FieldData) it.next();
        }
        return result;
    }

    public void mergeData(EntityData[] entitiesData,
                          EntityData[] externalFieldsData,
                          Collection gridData) {
        //if same entity came in entitiesData and in externalFieldsData, entitiesData should rewrite it
        if(externalFieldsData != null) {
            for(int i = 0; i < externalFieldsData.length; i++) {
                String externalFieldEntityName = externalFieldsData[i]
                        .getEntityID();
                if (fullEntitiesData.containsKey(externalFieldEntityName)) {
                    Map fieldsData = new HashMap();
                    EntityData existingData = (EntityData) fullEntitiesData.
                                                   get(externalFieldEntityName);
                    addFieldsToMap(fieldsData, existingData.getFields());
                    addFieldsToMap(fieldsData, externalFieldsData[i].getFields());
                    existingData.setFields(collectFields(fieldsData));
                }
                else {
                    fullEntitiesData.put(externalFieldEntityName,
                                                        externalFieldsData[i]);
                }
                externalFieldsEntities.add(externalFieldEntityName);
                clearFormDataConsumptionForEntity(externalFieldEntityName);
            }
        }
        if(entitiesData != null) {
            for(int i = 0; i < entitiesData.length; i++) {
                String entityName = entitiesData[i].getEntityID();
                fullEntitiesData.put(entityName, entitiesData[i]);
                externalFieldsEntities.remove(
                        entityName);//if data came for entity, it is not in externalFieldsEntities anymore
                clearFormDataConsumptionForEntity(entityName);
            }
        }
        if(gridData != null) {
            for(Iterator iterator = gridData.iterator(); iterator.hasNext();) {
                GridData data = (GridData) iterator.next();
                gridDataMap.put(data.getEntityName(), data);
                clearGirdDataConsumptionForEntity(data.getEntityName());
            }
        }
    }

    public void clearData(String entity) {
        fullEntitiesData.remove(entity);
        gridDataMap.remove(entity);
    }

    public void clearAllData() {
        fullEntitiesData.clear();
        gridDataMap.clear();
    }

    public EntityData getData(String entity) {
        return (EntityData) fullEntitiesData.get(entity);
    }

    public GridData getGridData(String entity) {
        return (GridData) gridDataMap.get(entity);
    }

    public void clearDataConsumptions() {
        dataConsumedByForm.clear();
        dataConsumedByGrid.clear();
    }

    public void addFormDataConsumption(String entityID, String formID) {
        addConsumption(dataConsumedByForm, entityID, formID);
    }

    public void addGridDataConsumption(String entityID, String formID) {
        addConsumption(dataConsumedByGrid, entityID, formID);
    }

    public boolean wasDataConsumedByForm(String entityID, String formID) {
        return wasConsumed(dataConsumedByForm, entityID, formID);
    }

    public boolean wasDataConsumedByGrid(String entityID, String formID) {
        return wasConsumed(dataConsumedByGrid, entityID, formID);
    }

    private static void addConsumption(Map elementsMap, String entityID,
                                       String formID) {
        Object forms = elementsMap.get(entityID);
        Set formsSet;
        if(forms == null) {
            formsSet = new HashSet();
            elementsMap.put(entityID, formsSet);
        } else {
            formsSet = (Set) forms;
        }
        formsSet.add(formID);
    }

    private static boolean wasConsumed(Map elementsMap, String entityID,
                                       String formID) {
        boolean ret = false;
        Object forms = elementsMap.get(entityID);
        if(forms != null) {
            Set formsSet = (Set) forms;
            ret = formsSet.contains(formID);
        }
        return ret;
    }

    private void clearFormDataConsumptionForEntity(String entityID) {
        clearConsumptions(dataConsumedByForm, entityID);
    }

    private void clearGirdDataConsumptionForEntity(String entityID) {
        clearConsumptions(dataConsumedByGrid, entityID);
    }

    private static void clearConsumptions(Map elementsMap, String entityID) {
        Object forms = elementsMap.get(entityID);
        if(forms != null) {
            Set formsSet = (Set) forms;
            formsSet.clear();
        }
    }

    public boolean isEntityDataInExternalFields(String entityName) {
        return externalFieldsEntities.contains(entityName);
    }
}
