/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 */

package org.seaborne.delta.cmds;

import java.io.InputStream ;

import arq.cmdline.ModDatasetAssembler;
import jena.cmd.ArgDecl;
import jena.cmd.CmdException;
import jena.cmd.CmdGeneral ;
import org.apache.jena.atlas.logging.LogCtl ;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.sparql.core.DatasetGraphFactory;
import org.apache.jena.sys.JenaSystem;
import org.apache.jena.system.Txn;
import org.seaborne.delta.Id;
import org.seaborne.patch.RDFPatch;
import org.seaborne.patch.RDFPatchOps;

/** Apply patches to a base RDF file (or empty dataset) . */
public class patch2rdf extends CmdGeneral
{
    static { JenaSystem.init(); LogCtl.setCmdLogging() ; }

    protected ModDatasetAssembler modDataset  =   new ModDatasetAssembler();
    protected ArgDecl dataDecl                = new ArgDecl(ArgDecl.HasValue, "data") ;

    public static void main(String... args) {
        new patch2rdf(args).mainRun();
    }

    public patch2rdf(String[] argv) {
        super(argv) ;
        super.addModule(modDataset) ;
        super.add(dataDecl);
    }

    @Override
    protected String getSummary() {
        return getCommandName()+"[--data QUADS | --desc ASSEMBLER ]  FILE..." ;
    }

    @Override
    protected void processModulesAndArgs() {
        super.processModulesAndArgs();
        if ( modDataset.getAssemblerFile() != null && super.hasArg(dataDecl) )
            throw new CmdException("Both an assembler file and a data file specificed");

    }

    @Override
    protected void exec() {
        DatasetGraph dsg;

        boolean writeOnFinish = false;

        // Data.
        if ( modDataset.getAssemblerFile() != null )
            dsg = modDataset.getDatasetGraph();
        else {
            dsg = DatasetGraphFactory.createTxnMem();
            if ( super.hasArg(dataDecl) ) {
                getValues(dataDecl).forEach(fn->{
                    Txn.executeWrite(dsg, ()->RDFDataMgr.read(dsg, fn));
                });
            }
            writeOnFinish = true;
        }

        // Patches
        if ( getPositional().isEmpty() )
            execOne(System.in);

        getPositional().forEach(fn->{
            // Check patch threading?
            RDFPatch patch = RDFPatchOps.read(fn);
            if ( isVerbose() ) {
                System.err.printf("# Patch id=%s", Id.str(patch.getId()));
                if ( patch.getPrevious() != null )
                    System.err.printf(" prev=%s", Id.str(patch.getPrevious()));
                System.err.println();
            }
            apply(dsg, patch);
        });

        if ( writeOnFinish )
            Txn.executeRead(dsg, ()->RDFDataMgr.write(System.out, dsg, Lang.TRIG));
    }

    private void apply(DatasetGraph dsg, RDFPatch patch) {
        RDFPatchOps.applyChange(dsg, patch);
    }

    private void execOne(InputStream input) {
        throw new CmdException("From InputStream (inc stdin) not yet supported");
    }

    @Override
    protected String getCommandName() {
        return "patch2rdf";
    }

}

@@ -719,38 +719,8 @@
 s;%0A%0A
-import java.io.InputStream ;%0A%0A
 impo
@@ -836,17 +836,16 @@
 dGeneral
- 
 ;%0Aimport
@@ -881,17 +881,16 @@
 g.LogCtl
- 
 ;%0Aimport
@@ -1297,17 +1297,16 @@
 dataset)
- 
 . */%0Apub
@@ -1400,17 +1400,16 @@
 ogging()
- 
 ; %7D%0A%0A   
@@ -1452,18 +1452,16 @@
 taset  =
-  
  new Mod
@@ -1565,17 +1565,16 @@
  %22data%22)
- 
 ;%0A%0A    p
@@ -1717,17 +1717,16 @@
 er(argv)
- 
 ;%0A      
@@ -1754,17 +1754,16 @@
 Dataset)
- 
 ;%0A      
@@ -1909,17 +1909,16 @@
 EMBLER %5D
- 
  FILE...
@@ -1918,17 +1918,16 @@
 FILE...%22
- 
 ;%0A    %7D%0A
@@ -2190,16 +2190,14 @@
 cifi
-c
 ed%22);%0A
-%0A
     
@@ -2800,16 +2800,18 @@
 mpty() )
+ %7B
 %0A       
@@ -2819,27 +2819,94 @@
     
-execOne(System.in);
+RDFPatch patch = RDFPatchOps.read(System.in);%0A            apply(dsg, patch);%0A        %7D
 %0A%0A  
@@ -3600,143 +3600,8 @@
  %7D%0A%0A
-    private void execOne(InputStream input) %7B%0A        throw new CmdException(%22From InputStream (inc stdin) not yet supported%22);%0A    %7D%0A%0A
     
@@ -3684,11 +3684,10 @@
 ;%0A    %7D%0A
-%0A
 %7D%0A

Support reading from stdin.