package org.commcare.core.process;

import org.commcare.core.interfaces.UserSandbox;
import org.commcare.data.xml.DataModelPullParser;
import org.commcare.data.xml.TransactionParser;
import org.commcare.data.xml.TransactionParserFactory;
import org.commcare.xml.CaseXmlParser;
import org.commcare.xml.LedgerXmlParsers;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;

/**
 * Utility methods for processing XML transactions against a user sandbox.
 * This was written to make TouchForms XML submissions easier to perform. Only processes
 * blocks that need to be transacted against the user record (IE cases and ledgers at the moment).
 * This should be used when you have a raw input stream of the XML; FormRecordProcessor on Android
 * should be used when you have a FormRecord object
 *
 * Created by wpride1 on 7/21/15.
 */
public class XmlFormRecordProcessor {

    public static void process(final UserSandbox sandbox, InputStream stream) throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException, StorageFullException {
        process(sandbox, stream, new TransactionParserFactory() {
            public TransactionParser getParser(KXmlParser parser) {
                if (LedgerXmlParsers.STOCK_XML_NAMESPACE.equals(parser.getNamespace())) {
                    return new LedgerXmlParsers(parser, sandbox.getLedgerStorage());
                } else if ("case".equalsIgnoreCase(parser.getName())) {
                    return new CaseXmlParser(parser, sandbox.getCaseStorage());
                }
                return null;
            }

        });

    }

    public static void process(UserSandbox sandbox, InputStream stream, TransactionParserFactory factory) throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException, StorageFullException {
        InputStream is = stream;

        DataModelPullParser parser = new DataModelPullParser(is, factory, true, true);

        parser.parse();
    }
}

@@ -1353,25 +1353,16 @@
 process(
-sandbox, 
 stream, 
@@ -1902,37 +1902,16 @@
 process(
-UserSandbox sandbox, 
 InputStr
@@ -2089,42 +2089,8 @@
 n %7B%0A
-        InputStream is = stream;%0A%0A
     
@@ -2146,18 +2146,22 @@
 lParser(
-i
 s
+tream
 , factor
@@ -2176,17 +2176,16 @@
  true);%0A
-%0A
         

remove unused method param