package com.queplix.core.utils.jxb;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>Base class for all JXB objects</p>
 *
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.2 $ $Date: 2006/04/03 06:47:56 $
 */

public abstract class JXBObject implements java.io.Serializable {
    private List<String> nameList = new ArrayList<String>();
    private Map<String, Object> nameTable = new HashMap<String, Object>();

    /**
     * Get position of child object
     *
     * @param name child object name
     * @return child object position
     */
    public int getPos(String name) {
        return nameList.indexOf(name);
    }

    /**
     * Get child object
     *
     * @param name child object name
     * @return child object
     */
    public Object getObject(String name) {
        return nameTable.get(name);
    }

    /**
     * Get child object
     *
     * @param name child object name
     * @return child object
     */
    public Set<String> getObjectNames() {
        return nameTable.keySet();
    }


    /**
     * Put child object
     *
     * @param name child object name
     * @param o    child object
     */
    public void putObject(String name, Object o) {
        nameList.add(name);
        nameTable.put(name, o);
    }

    /**
     * Get string represents owner object
     *
     * @return string
     */
    public String toString() {
        StringBuffer sb = new StringBuffer();
        Method[] methods = getClass().getMethods();
        for(int i = 0; i < methods.length; i++) {
            String name = methods[i].getName();
            if(name.startsWith("get")
                    && methods[i].getParameterTypes().length == 0) {
                try {
                    Object o = methods[i].invoke(this, (Object[]) null);
                    sb.append(name);
                    if(o != null) {
                        if(o.getClass().isArray()) {
                            Object[] oo = (Object[]) o;
                            sb.append("=\n[\n");
                            for(int j = 0; j < oo.length; j++) {
                                if(oo[j] != null) {
                                    sb.append(oo[j].toString()).append("\n");
                                }
                            }
                            sb.deleteCharAt(sb.length() - 1);
                        } else {
                            sb.append("=[").append(o.toString());
                        }
                    } else {
                        sb.append("=[NULL");
                    }
                    sb.append("]\n");
                } catch (Exception ex) {
                }
            }
        }
        return sb.toString();
    }
}