/*
 * LensKit, an open source recommender systems toolkit.
 * Copyright 2010-2013 Regents of the University of Minnesota and contributors
 * Work on LensKit has been funded by the National Science Foundation under
 * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.grouplens.lenskit.cli;

import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.grouplens.grapht.Component;
import org.grouplens.grapht.Dependency;
import org.grouplens.grapht.graph.DAGNode;
import org.grouplens.grapht.solver.SolverException;
import org.grouplens.grapht.util.Providers;
import org.grouplens.lenskit.core.*;
import org.grouplens.lenskit.data.dao.EventDAO;
import org.grouplens.lenskit.data.pref.PreferenceDomain;
import org.grouplens.lenskit.eval.graph.GraphDumper;
import org.grouplens.lenskit.inject.RecommenderGraphBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Command that draws a diagram of a recommender configuration.
 *
 * @since 2.1
 * @author <a href="http://www.grouplens.org">GroupLens Research</a>
 */
@CommandSpec(name = "graph", help = "diagram a recommender configuration")
public class Graph implements Command {
    private final Logger logger = LoggerFactory.getLogger(Graph.class);
    private final Namespace options;
    private final ScriptEnvironment environment;

    public Graph(Namespace opts) {
        options = opts;
        environment = new ScriptEnvironment(opts);
    }

    public List<File> getConfigFiles() {
        return options.get("config");
    }

    public File getOutputFile() {
        return options.get("output_file");
    }

    private LenskitConfiguration makeDataConfig() {
        LenskitConfiguration config = new LenskitConfiguration();
        config.bind(EventDAO.class).toProvider(Providers.<EventDAO>of(null, EventDAO.class));
        String dspec = options.getString("domain");
        if (dspec != null) {
            PreferenceDomain domain = PreferenceDomain.fromString(dspec);
            config.bind(PreferenceDomain.class).to(domain);
        }
        return config;
    }

    private DAGNode<Component, Dependency> getModel() throws IOException, RecommenderConfigurationException {
        File file = options.get("model_file");
        if (file == null) {
            return null;
        }

        logger.info("loading model from {}", file);
        LenskitRecommenderEngineLoader loader = LenskitRecommenderEngine.newLoader();
        loader.setValidationMode(EngineValidationMode.DEFERRED)
              .addConfiguration(makeDataConfig());
        for (LenskitConfiguration config: environment.loadConfigurations(getConfigFiles())) {
            loader.addConfiguration(config);
        }
        LenskitRecommenderEngine engine = loader.load(file);
        return engine.getGraph();
    }

    private DAGNode<Component,Dependency> makeGraph() throws IOException, RecommenderConfigurationException {
        RecommenderGraphBuilder rgb = new RecommenderGraphBuilder();
        rgb.addConfiguration(makeDataConfig());
        for (LenskitConfiguration config: environment.loadConfigurations(getConfigFiles())) {
            rgb.addConfiguration(config);
        }

        try {
            return rgb.buildGraph();
        } catch (SolverException e) {
            throw new RecommenderConfigurationException("Cannot configure recommender", e);
        }
    }

    @Override
    public void execute() throws IOException, RecommenderConfigurationException {
        DAGNode<Component, Dependency> graph = getModel();
        if (graph == null) {
            graph = makeGraph();
        }
        File output = getOutputFile();
        logger.info("writing graph to {}", output);
        GraphDumper.renderGraph(graph, output);
    }

    public static void configureArguments(ArgumentParser parser) {
        ScriptEnvironment.configureArguments(parser);
        parser.addArgument("-o", "--output-file")
              .type(File.class)
              .metavar("FILE")
              .setDefault(new File("recommender.dot"))
              .help("write recommender diagram to FILE");
        parser.addArgument("--domain")
              .metavar("DOMAIN")
              .help("specify preference domain");
        parser.addArgument("--model-file")
              .metavar("FILE")
              .type(File.class)
              .help("load saved model from FILE");
        parser.addArgument("config")
              .type(File.class)
              .metavar("CONFIG")
              .nargs("*")
              .help("load algorithm configuration from file CONFIG");
    }
}

@@ -2936,58 +2936,153 @@
     
-private DAGNode%3CComponent, Dependency%3E getModel() 
+/**%0A     * Load a configuration graph from a recommender model.%0A     * @param file The model file.%0A     * @return The recommender graph.%0A     * @
 thro
@@ -3087,33 +3087,47 @@
 rows IOException
-,
+%0A     * @throws
  RecommenderConf
@@ -3148,121 +3148,136 @@
 tion
- %7B
 %0A     
-   File file = options.get(%22m
+*/%0A    private DAGNode%3CComponent, Dependency%3E loadM
 odel
-_file%22);%0A        if (file == null) %7B%0A            return null;%0A        %7D%0A
+(File file) throws IOException, RecommenderConfigurationException %7B
 %0A   
@@ -3769,32 +3769,243 @@
 Graph();%0A    %7D%0A%0A
+    /**%0A     * Build a configured recommender graph from the specified configurations.%0A     * @return The configuration graph.%0A     * @throws IOException%0A     * @throws RecommenderConfigurationException%0A     */%0A
     private DAGN
@@ -4030,24 +4030,27 @@
 ndency%3E make
+New
 Graph() thro
@@ -4651,32 +4651,84 @@
 tionException %7B%0A
+        File modelFile = options.get(%22model_file%22);%0A
         DAGNode%3C
@@ -4759,22 +4759,42 @@
 raph
- = getModel();
+;%0A        if (modelFile != null) %7B
 %0A   
@@ -4802,26 +4802,56 @@
     
-if (
+    
 graph =
-= null)
+ loadModel(modelFile);%0A        %7D else
  %7B%0A 
@@ -4873,16 +4873,19 @@
 h = make
+New
 Graph();

Clean up and document graph-loading logic