/*
 * 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;

import com.queplix.core.error.GenericSystemException;

import java.util.Date;

/**
 * <p>EQL object abstract class</p>
 *
 * @author Baranov Andrey [ALB]
 * @version $Revision: 1.2 $ $Date: 2006/01/20 15:19:10 $
 */

public abstract class EQLObject
        implements EQLReqSubOpMember, java.io.Serializable {

    public abstract Object getObject();

    public abstract int getSqlType();

    /**
     * Get instance of EQLObject
     *
     * @param value EQLObject constructor parameter
     * @return instance of EQLObject
     */
    public static EQLObject getInstance(Object value) {

        if(value == null) {
            return EQLNullObject.getInstance();
        } else if(value instanceof Number) {
            return new EQLNumberObject((Number) value);
        } else if(value instanceof String) {
            return new EQLStringObject((String) value);
        } else if(value instanceof java.sql.Time) {
            return new EQLTimeObject((java.sql.Time) value);
        } else if(value instanceof Date) {
            return new EQLDateObject((Date) value);
        } else if(value instanceof char[]) {
            return new EQLMemoObject((char[]) value);
        } else if(value instanceof byte[]) {
            return new EQLBinaryObject((byte[]) value);
        } else {
            throw new GenericSystemException(
                    "Can't get EQL object for '" + value.getClass() + "'");
        }
    }

    public int hashCode() {
        return getObject().hashCode();
    }

    public boolean equals(Object o) {
        if(o == null || !(o instanceof EQLObject)) {
            return false;
        }

        if(o == this) {
            return true;
        }

        EQLObject obj = (EQLObject) o;
        return (getObject() == null && obj.getObject() == null) ||
                (getObject() != null && obj.getObject() != null && getObject()
                        .equals(obj.getObject()));
    }

    /**
     * Builds special short string.
     * It can be used for logging...
     *
     * @return String
     */
    public String toShortString() {
        String s = toString();
        if(s != null && s.length() > 100) {
            s = s.substring(0, 100) + "...";
        }
        return s;
    }
}
