#!/usr/bin/env ruby

require 'airstream'

def self.exit(status)
  Airstream::Io.show_input
  puts "\n" # clear output
  super status
end

options = {
  reciever: '192.168.0.123',
  quiet: false,
  verbose: false,
  # disable_local_http: true
}

CONFIG_FILE = File.join(ENV['HOME'] || '', '.airstreamrc')

EXIT_OK = 0
EXIT_ERROR = 1
EXIT_NO_HOST = 68

UPDATE_TIMEOUT = 0.2

if File.exists? CONFIG_FILE
  options_config = YAML.load_file(CONFIG_FILE)
  options.merge!(options_config)
else
  File.open(CONFIG_FILE,'w') { |file| YAML::dump(options,file) }
  STDERR.puts "Initialized configuration file in #{CONFIG_FILE}"
end

option_parser = OptionParser.new do |opts|
  executable_name = File.basename($PROGRAM_NAME)
  opts.banner = "offer a video file to an airplay device

Usage: #{executable_name} [options] [url|path/]filename

Basic options: (configure default in ~/.airstreamrc)
"

  opts.on("-o RECIEVER",
   "the airplay-device ip-address or domain") do |reciever|
    options[:reciever] = reciever
  end

  opts.on("-q","--quiet",
   "prevent most of the output") do |quiet|
    options[:quiet] = quiet
  end

  opts.on("--verbose",
   "additional output") do |verbose|
    options[:verbose] = verbose
  end

  # opts.on("--disable-use-httpd",
  #  "do not create httpd to offer local files") do |disable_httpd|
  #   options[:disable_local_httpd] = true
  # end

  opts.on("-v", "--version",
   "output version information then quit") do |path|
    puts "airstream v" + Airstream::VERSION
    exit EXIT_OK
  end
end

if ARGV.empty?
  STDERR.puts "No arguments given"
  STDERR.puts option_parser
  exit EXIT_ERROR
end
playlist = ARGV

begin

  option_parser.parse!

  unless options[:reciever]
    STDERR.puts "No host given"
    exit EXIT_NO_HOST
  end

  io = Airstream::Io.new
  io.quiet = options[:quiet]
  io.verbose = options[:verbose]
  node = Airstream::Node.new options[:reciever]
  device = Airstream::Device.new node
  io.puts "loading can take a few seconds..."
  playlist.map! { |file| Airstream::Video.new(file) }
  player = Airstream::Player.new device, playlist

  io.puts "=> press ["+Airstream::Io::KEY_QUIT+"] to exit airstream"
  Airstream::Io.hide_input
  total_duration = player.duration
  pbar = ProgressBar.create({ format: '%t |%b%i| %p%%', total: total_duration })
  begin # reconsider playing...
    sleep UPDATE_TIMEOUT
    formatted_time = Time.at(player.elapsed_time).gmtime.strftime('%R:%S')
    pbar.title = "#{player.current_title} #{formatted_time}"
    pbar.progress = [player.elapsed_time, total_duration].min
    io.catch_input
    player.update io
  end until io.quit? || player.finished?
  pbar.finish

rescue Airplay::Protocol::InvalidMediaError
  STDERR.puts
  STDERR.puts "invalid media file"
  exit EXIT_ERROR
# rescue NoMethodError # @FIX webrick raises no method error
#   STDERR.puts
#   STDERR.puts "file host shutdown"
#   exit EXIT_OK
rescue Interrupt
  STDERR.puts
  STDERR.puts "exiting"
  exit EXIT_ERROR
rescue OptionParser::InvalidArgument => ex
  STDERR.puts ex.message
  STDERR.puts option_parser
  exit EXIT_ERROR
ensure
  Airstream::Io.show_input
end

exit EXIT_OK

