require 'ipcrypt/engine'
require 'thor'
require 'csv'
module IPCrypt
  class CLI < Thor
    class_option :key, aliases: '-k', type: :string, :desc => '16-byte key', required: true

    %w[encrypt decrypt].each do |crypt|
      desc "#{crypt} [CSV] [COLUMN]", "#{crypt.capitalize} IPv4 addresses from a CSV file"
      define_method crypt do |file, column|
        csv = CSV.read(file, headers: true)
        puts csv.headers * ?,

        _crypted = Engine.new(*csv[column]).send(crypt, options[:key])

        CSV.foreach(file, headers: true).with_index do |row, i|
          puts csv.headers.map {|h| h == column ? _crypted[i] : row[h]} * ?,
        end
      end
    end

    def self.help(shell, subcommand = false)
      list = printable_commands(true, subcommand)
      Thor::Util.thor_classes_in(self).each do |klass|
        list += klass.printable_commands(false)
      end
      list.sort! { |a, b| a[0] <=> b[0] }
      list.reject! { |e| /.*help.*/.match? e.first }
      list.map! {|c| c.map {|s| s.gsub('decrypt', ?d).gsub('encrypt', ?e)} }

      if defined?(@package_name) && @package_name
        shell.say "#{@package_name} commands:"
      else
        shell.say "Commands:"
      end

      shell.print_table(list, :indent => 2, :truncate => true)
      shell.say
      class_options_help(shell)
    end
  end
end