/*
 * 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.app.vo;

import com.google.gwt.user.client.rpc.IsSerializable;

/**
 * Entity Meta
 *
 * @author Sultan Tezadov
 */
public class EntityMeta implements IsSerializable {
    private FieldMeta[] fields;
    private String entityID;

    public EntityMeta(String entityID, FieldMeta[] fields) {
        this.entityID = entityID;
        if(fields != null) {
            this.fields = fields;
        } else {
            this.fields = new FieldMeta[0];
        }
    }

    public EntityMeta() {
        this("", null);
    }

    /**
     * @return fields meta. couldn't be null
     */
    public FieldMeta[] getFields() {
        return fields;
    }

    public void setFields(FieldMeta[] fields) {
        if(fields != null) {
            this.fields = fields;
        }
    }

    public String getEntityID() {
        return entityID;
    }

    public void setEntityID(String entityID) {
        this.entityID = entityID;
    }

    public int getFieldIndex(String fieldID) {
        int i = fields.length - 1;
        while(i > -1 && !fields[i].getFieldID().equals(fieldID)) {
            i--;
        }
        return i;
    }

    public FieldMeta getField(String fieldID) {
        int index = getFieldIndex(fieldID);
        if(index >= 0) {
            return fields[index];
        } else {
            return null;
        }
    }

    public void removeField(String fieldId) {
        int index = getFieldIndex(fieldId);
        if(index >= 0 && index < fields.length) {
            FieldMeta[] newFields = new FieldMeta[fields.length - 1];
            for(int i = 0, newCounter = 0; i < fields.length; i++) {
                if(i != index) {
                    newFields[newCounter] = fields[i];
                    newCounter++;
                }
            }
            fields = newFields;
        }
    }
}
