
/*
 * 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.EnumSet;
import java.util.Map;

import org.jsimpledb.SessionMode;
import org.jsimpledb.cli.CliSession;
import org.jsimpledb.kv.util.XMLSerializer;
import org.jsimpledb.parse.Parser;
import org.jsimpledb.util.ParseContext;

public class KVLoadCommand extends AbstractKVCommand {

    public KVLoadCommand() {
        super("kvload file.xml:file");
    }

    @Override
    public String getHelpSummary() {
        return "Load key/value pairs from an XML file";
    }

    @Override
    public String getHelpDetail() {
        return "Imports key/value pairs from an XML file created previously via `kvsave'. Does not remove any key/value pairs"
          + "already in the database."
          + "\n\nWARNING: this command can corrupt a JSimpleDB database.";
    }

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

    @Override
    public EnumSet<SessionMode> getSessionModes() {
        return EnumSet.of(SessionMode.KEY_VALUE);
    }

    @Override
    public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) {
        final File file = (File)params.get("file.xml");
        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 XMLSerializer(session.getKVTransaction()).read(input);
                }
                session.getWriter().println("Read " + count + " key/value pairs from `" + file + "'");
            }
        };
    }
}


@@ -303,16 +303,55 @@
 ession;%0A
+import org.jsimpledb.kv.KVTransaction;%0A
 import o
@@ -382,24 +382,24 @@
 Serializer;%0A
-
 import org.j
@@ -569,16 +569,25 @@
 %22kvload 
+-R:reset 
 file.xml
@@ -865,11 +865,11 @@
 oes 
-not
+NOT
  rem
@@ -929,16 +929,100 @@
 database
+ unless the %60-R' flag is given, in which case the database is completely wiped first
 .%22%0A     
@@ -1522,24 +1522,83 @@
 %3E params) %7B%0A
+        final boolean reset = params.containsKey(%22reset%22);%0A
         fina
@@ -1784,16 +1784,162 @@
 ption %7B%0A
+                final KVTransaction kvt = session.getKVTransaction();%0A                if (reset)%0A                    kvt.removeRange(null, null);%0A
         
@@ -2116,34 +2116,11 @@
 zer(
-session.getKVTransaction()
+kvt
 ).re

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