package org.infinispan.cli.commands;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import org.aesh.command.Command;
import org.aesh.command.CommandDefinition;
import org.aesh.command.CommandException;
import org.aesh.command.CommandResult;
import org.aesh.command.impl.completer.FileOptionCompleter;
import org.aesh.command.option.Arguments;
import org.aesh.command.option.Option;
import org.aesh.io.Resource;
import org.infinispan.cli.impl.ContextAwareCommandInvocation;
import org.infinispan.cli.impl.ExitCodeResultHandler;
import org.infinispan.cli.logging.Messages;
import org.infinispan.commons.util.StringPropertyReplacer;
import org.kohsuke.MetaInfServices;

/**
 * @author Tristan Tarrant &lt;tristan@infinispan.org&gt;
 * @since 10.0
 **/
@MetaInfServices(Command.class)
@CommandDefinition(name = "run", description = "Reads and executes commands from one or more files", resultHandler = ExitCodeResultHandler.class)
public class Run extends CliCommand {

   @Arguments(required = true, completer = FileOptionCompleter.class)
   private List<Resource> arguments;

   @Option(shortName = 'h', hasValue = false, overrideRequired = true)
   protected boolean help;

   @Override
   public boolean isHelp() {
      return help;
   }

   @Override
   public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException {
      if (arguments != null && arguments.size() > 0) {
         for (Resource resource : arguments) {
            int lineCount = 0;
            String line = null;
            try (BufferedReader br = new BufferedReader("-".equals(resource.getName()) ? new InputStreamReader(System.in) : new InputStreamReader(resource.read()))) {
               for (line = br.readLine(); line != null; line = br.readLine()) {
                  lineCount++;
                  if (!line.startsWith("#")) {
                     invocation.executeCommand("batch " + StringPropertyReplacer.replaceProperties(line));
                  }
               }
            } catch (Exception e) {
               throw Messages.MSG.batchError(lineCount, line, e);
            }
         }
      }
      return CommandResult.SUCCESS;
   }
}
