package com.aelfengard.i3;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class LPCMixed {

    private final Object value;
    
    public LPCMixed(Object value) {
        while (value instanceof LPCMixed) {
            value = ((LPCMixed) value).value;
        }
        this.value = value;
    }
    
    public Object asObject() {
        return value;
    }
    
    public String asString() {
        if (value == null) {
            return null;
        }
        if (value instanceof String) {
            return (String) value;
        }
        if (new Integer(0).equals(value)) {
            return null;
        }
        return String.valueOf(value);
    }
    
    public Integer asInteger() {
        return asInteger(null);
    }
    
    public Integer asInteger(Integer def) {
        if (value instanceof Integer) {
            return (Integer) value;
        }
        return def;
    }

    public List<LPCMixed> asList() {
        if (value instanceof List) {
            List list = (List) value;
            List<LPCMixed> ret = new ArrayList<LPCMixed>(list.size());
            for (Object o : list) {
                ret.add((LPCMixed) o);
            }
            return ret;
        }
        else {
            return null;
        }
    }
    
    public Map<LPCMixed,LPCMixed> asMap(boolean emptyIfNull) {
        Map<LPCMixed,LPCMixed> ret = asMap();
        if (ret != null) {
            return ret;
        }
        return Collections.emptyMap();
    }
    
    public Map<LPCMixed,LPCMixed> asMap() {
        if (value instanceof Map) {
            Map map = (Map) value;
            Map<LPCMixed,LPCMixed> ret = new LinkedHashMap<LPCMixed,LPCMixed>(map.size());
            Iterator iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                ret.put((LPCMixed) entry.getKey(), (LPCMixed) entry.getValue());
            }
            return ret;
        }
        return null;
    }
    
    public String toString() {
        return asString();
    }

}