/*
 * 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.integrator.entity;

import com.queplix.core.client.app.vo.FieldData;
import com.queplix.core.client.app.vo.FieldMeta;
import com.queplix.core.client.app.vo.RowData;
import com.queplix.core.integrator.ActionContext;
import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.modules.config.utils.EntityHelper;
import com.queplix.core.utils.StringHelper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Help to work with entity.
 *
 * @author Sergey Kozmin
 * @since 14.03.2007
 */
public class EntityOperationsHelper {
    /**
     * Method Integrated response object and retrieve array of rows for 3.0 grid.
     *
     * @param integrResp integrated response from EntityFacade
     * @param ls         user logon session. Some grid values might be customized according to user properties.
     * @param ctx        servlet context
     * @return array of RowData objects
     * @throws IllegalControlTypeException thrown if control has incorrect described type or invalid data for described type
     * @throws CouldntGetEJBException      thrown if method could not retrieve some ejb
     */
    public static RowData[] retrieveGridRowsDataFromResult(
            IntegratedRecordSet integrResp, LogonSession ls, ActionContext ctx)
            throws IllegalControlTypeException {

        RowData[] rowSet = new RowData[integrResp.getRowsCount()];

        ArrayList<String> columnValues = new ArrayList<String>();
        Set<String> gridMetas = integrResp.getGridFields();

        Map<String, FieldMeta> responseMeta = integrResp.getRecordMeta();

        String rowIDName = integrResp.getPkeyFieldName();
        FieldMeta rowIDFieldMeta = responseMeta.get(rowIDName);
        int counter = 0;
        for(IntegratedRecord record : integrResp.getRecordSet()) {
            //retrieve field values
            Map<String, FieldData> fieldValues = record.getFieldSet();
            for(String fieldName : gridMetas) {
                String gridValue = EntitySerializeHelper
                        .getStringRepresentationForGrid(fieldValues.get(
                                fieldName),
                                responseMeta.get(fieldName), ls, ctx);
                columnValues.add(gridValue);
            }

            //create next row data for grid
            Long rowID;
            if(rowIDFieldMeta != null) {
                rowID = Long.parseLong(
                        EntitySerializeHelper.getValueStringRepresentation(
                                fieldValues.get(rowIDName), rowIDFieldMeta));
            } else {
                rowID = (long) counter;
            }
            RowData rowdata = new RowData(rowID, columnValues.toArray(
                    new String[columnValues.size()]));
            rowSet[counter++] = rowdata;
            columnValues.clear();
        }

        return rowSet;
    }

    public static RowData retrieveGridRowsDataFromResult(String entityName,
                                                         Collection<FieldData> fields,
                                                         EntityViewHelper.FieldsModificator mode,
                                                         LogonSession ls,
                                                         ActionContext ctx)
            throws IllegalControlTypeException {
        Map<String, FieldMeta> entityMeta = EntityViewHelper.getMetaForEntity(
                entityName,
                mode, false, ls, ctx);

        Map<String, FieldData> entityData = new HashMap<String, FieldData>(
                entityMeta.size());
        for(FieldData field : fields) {
            entityData.put(field.getFieldID(), field);
        }

        List<String> list = new ArrayList<String>(entityMeta.size());
        for(String fieldName : entityMeta.keySet()) {
            FieldData fieldData = entityData.get(fieldName);
            if(fieldData != null) {
                String gridValue = EntitySerializeHelper
                        .getStringRepresentationForGrid(fieldData,
                                entityMeta.get(fieldName), ls, ctx);
                list.add(gridValue);
            } else {
                list.add("");
            }
        }

        return new RowData(null, list.toArray(new String[list.size()]));
    }

    public static String getEntityNameFromFormID(String formID) {
        if(formID.lastIndexOf(EntityHelper.FORM_NAME_SEPARATOR) > 0) {
            return formID.substring(formID.lastIndexOf(
                    EntityHelper.FORM_NAME_SEPARATOR) + EntityHelper
                    .FORM_NAME_SEPARATOR.length());
        } else {
            return formID;
        }
    }

    public static String getFocusNameFromFormID(String formID) {
        return formID.substring(0, formID.indexOf(
                EntityHelper.FORM_NAME_SEPARATOR));
    }

    public static String getTabNameFromFormID(String formID) {
        return formID.substring(0, formID.lastIndexOf(
                EntityHelper.FORM_NAME_SEPARATOR));
    }

    public static String getLocalizedServerMessage(String messageID,
                                                   Object[] args, String langID,
                                                   ActionContext ctx) {
        String localizedMessage = ctx.getCaptionManager().getServerMessage(
                langID, messageID);
        return StringHelper.format(localizedMessage, args);
    }
}
