require 'file_mover/filter'
require 'file_mover/password'
require 'active_support/core_ext/class/attribute'

module FileMover

  # subclasses must implement #cmd(tmp_dir, pathes)
  # and target_pathes(tmp_dir,pathes)
  class Cmd < Filter
    include Password
    class_attribute :single_mode, instance_writer: false

    def filter_files tmp_dir, pathes
      if single_mode
        pathes.map{|path| _filter_files tmp_dir, path}.flatten 
      else
        _filter_files tmp_dir, pathes
      end
    end

    def to_s
      self.class.to_s
    end

    private
    def _filter_files tmp_dir, pathes 
      command = cmd tmp_dir, pathes
      logger.info{"#{self}: calling #{hide(command)}"}
      require 'open3'
      Open3.popen3(unmask(command)) do |stdin,stdout,stderr|
        threads = []
        threads << Thread.new do
          while out=stdout.gets do debug_out(out,"stdout: ") end
        end
        threads << Thread.new do
          while err=stderr.gets do debug_out(err,"stderr: ") end
        end
        threads.each &:join
      end
      target_pathes tmp_dir, pathes
    end

    def debug_out line, prefix
      logger.debug{"#{self}: #{prefix} #{line}"} if line && !line.strip.empty?
    end
  end
end
