package org.javarosa.core.model.instance;

import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.PrototypeFactory;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * @author ctsims
 */
public class ExternalDataInstance extends DataInstance {
    String reference;

    AbstractTreeElement root;
    InstanceBase base;

    public ExternalDataInstance() {
    }

    public ExternalDataInstance(String reference, String instanceid) {
        super(instanceid);
        this.reference = reference;
    }

    /**
     * Copy constructor
     */
    public ExternalDataInstance(ExternalDataInstance instance) {
        super(instance.getInstanceId());

        this.reference = instance.getReference();
        this.base = instance.getBase();
        this.root = instance.getRoot();
    }


    /*
     * (non-Javadoc)
     * @see org.javarosa.core.model.instance.DataInstance#isRuntimeEvaluated()
     */
    public boolean isRuntimeEvaluated() {
        return true;
    }


    public InstanceBase getBase() {
        return base;
    }

    public AbstractTreeElement getRoot() {
        return root;
    }

    public String getReference() {
        return reference;
    }

    public void readExternal(DataInputStream in, PrototypeFactory pf)
            throws IOException, DeserializationException {
        super.readExternal(in, pf);
        reference = ExtUtil.readString(in);
    }

    public void writeExternal(DataOutputStream out) throws IOException {
        super.writeExternal(out);
        ExtUtil.writeString(out, reference);
    }

    public DataInstance initialize(InstanceInitializationFactory initializer, String instanceId) {
        base = new InstanceBase(instanceId);
        root = initializer.generateRoot(this);
        base.setChild(root);
        return initializer.getSpecializedExternalDataInstance(this);
    }
}

@@ -936,24 +936,75 @@
 .getRoot();%0A
+        this.mCacheHost = instance.getCacheHost();%0A
     %7D%0A%0A%0A    
@@ -2048,20 +2048,21 @@
 ance(this);%0A
+%0A
     %7D%0A%7D%0A

Fix for cache hosts not being properly transfered with custom data instances