
/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb.cli.cmd;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

import org.jsimpledb.cli.CliSession;
import org.jsimpledb.core.util.XMLObjectSerializer;
import org.jsimpledb.parse.Parser;
import org.jsimpledb.util.ParseContext;

public class LoadCommand extends AbstractCommand {

    public LoadCommand() {
        super("load file.xml:file");
    }

    @Override
    public String getHelpSummary() {
        return "Load objects from an XML file";
    }

    @Override
    public String getHelpDetail() {
        return "Imports objects from an XML file created previously via `save'. Does not remove any objects already"
          + " in the database.";
    }

    @Override
    protected Parser<?> getParser(String typeName) {
        return "file".equals(typeName) ? new InputFileParser() : super.getParser(typeName);
    }

    @Override
    public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) {
        final File file = (File)params.get("file.xml");

        // Return import action
        return new CliSession.TransactionalAction() {
            @Override
            public void run(CliSession session) throws Exception {
                final int count;
                try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(file))) {
                    count = new XMLObjectSerializer(session.getTransaction()).read(input);
                }
                session.getWriter().println("Read " + count + " objects from `" + file + "'");
            }
        };
    }
}


@@ -470,16 +470,25 @@
 r(%22load 
+-R:reset 
 file.xml
@@ -748,11 +748,11 @@
 oes 
-not
+NOT
  rem
@@ -805,16 +805,100 @@
 database
+ unless the %60-R' flag is given, in which case the database is completely wiped first
 .%22;%0A    
@@ -1201,24 +1201,83 @@
 %3E params) %7B%0A
+        final boolean reset = params.containsKey(%22reset%22);%0A
         fina
@@ -1323,41 +1323,8 @@
 l%22);
-%0A%0A        // Return import action
 %0A   
@@ -1489,13 +1489,411 @@
 nal 
-int c
+Transaction tx = session.getTransaction();%0A                if (reset) %7B%0A                    int deleteCount = 0;%0A                    for (ObjId id : tx.getAll()) %7B%0A                        tx.delete(id);%0A                        deleteCount++;%0A                    %7D%0A                    session.getWriter().println(%22Deleted %22 + deleteCount + %22 object(s)%22);%0A                %7D%0A                final int readC
 ount
@@ -2017,17 +2017,21 @@
         
-c
+readC
 ount = n
@@ -2164,17 +2164,21 @@
 ead %22 + 
-c
+readC
 ount + %22
@@ -2180,25 +2180,27 @@
 t + %22 object
-s
+(s)
  from %60%22 + f

Add `-R' flag to the load CLI command.