module Piv

  class Shell
    def initialize(shell)
      @shell = shell
    end

    def say(message)
      use_color = $stdout.tty? ? :green : nil
      @shell.say message, use_color, true
    end

    def error(message)
      use_color = $stdout.tty? ? :red : nil

      begin
        orig_stdout, $stdout = $stdout, $stderr
        @shell.say message, use_color, true
      ensure
        $stdout = orig_stdout
      end
    end

    def print_exception(exception, message=nil)
      message ||= exception.message

      if ENV['DEBUG']
        error "#{exception.class.name} - #{message}"
        exception.backtrace.each {|line| error line }
      else
        error message
      end
    end

    def ask_password(message)
      begin
        require 'highline'
        @highline ||= HighLine.new $stdin

        if $stdin.tty?
          @highline.ask(message) {|q| q.echo = "*"}
        else
          @highline.ask(message)
        end
      rescue EOFError
        return ''
      end
    end
  end

end
