require 'json'
require 'tempfile'
require 'open3'
require 'fileutils'
require 'open-uri'

module JamRuby

  # Interact with external python tools to create jmep json
  class JmepManager

    @@log = Logging.logger[JmepManager]

    class << self

      def execute(jmep_text)

        json = nil

        if jmep_text.blank?
          return nil
        end

        py_root = APP_CONFIG.jmep_dir
        Dir.mktmpdir do |tmp_dir|

          output_json = File.join(tmp_dir, "jmep.json")
          input_text  = File.join(tmp_dir, "jmep.txt")

          # put JMEP text into input file
          File.open(input_text, 'w') { |file| file.write(jmep_text) }

          py_file = File.join(py_root, "jmepgen.py")
          @@log.info "Executing python source in #{py_file}, outputting to #{output_json})"

          # From http://stackoverflow.com/questions/690151/getting-output-of-system-calls-in-ruby/5970819#5970819:
          cli = "python #{py_file} -i '#{input_text}' -o '#{output_json}'"
          Open3.popen3(cli) do |stdin, stdout, stderr, wait_thr|
            pid = wait_thr.pid
            exit_status = wait_thr.value
            err = stderr.read(1000)
            out = stdout.read(1000)

            raise ArgumentError, "#{out} #{err}" if exit_status != 0

            json = File.read(output_json)
          end
        end

        json
      end

    end
  end
end
