#!/usr/bin/env ruby

require 'optparse'
require 'magento_remote'

# Sweet, sweet options.
options = {}

optparse = OptionParser.new do |opts|
  opts.banner = "Usage: magento_add_to_cart [OPTIONS]"

  opts.separator ""
  opts.separator "Magento shop options"

  opts.on('-u', '--customer USER', 'customer/username of shop.') do |u|
    options[:user] = u
  end
  opts.on('-p', '--password PASSWORD', 'password of customer account.') do |p|
    options[:pass] = p
  end
  opts.on('-b', '--base-uri URI', 'base URI of shop.') do |b|
    options[:base_uri] = b
  end

  opts.separator ""
  opts.separator "Product options"

  opts.on('-w', '--product-id PRODUCTID', 'product id of product to put in cart.') do |p|
    options[:product_id] = p
  end

  opts.on('-q', '--quantity QUANTITY', 'quantity of product to put in cart.') do |q|
    options[:quantity] = q
  end

  opts.on('-a', '--as-many-as-possible', 'try to order as many as possible.') do
    options[:amap] = true
  end

  opts.separator ""
  opts.separator "Output options"

  opts.on('-c', '--show-cart', 'show cart contents afterwards') do |c|
    options[:show_cart] = true
  end

  opts.on('-d', '--debug FILE', 'enable debugging output, STDOUT, or FILE if given') do |d|
    if d
      options[:debug] = d
    else
      options[:debug] = true
    end
  end

  opts.separator ""
  opts.separator "General options"

  opts.on_tail('--version', 'Show version.') do
    puts "magento_add_to_cart #{MagentoRemote::VERSION}"
    exit 0
  end
  opts.on('-h', '--help', 'Show help.') do
    puts opts
    exit 0
  end
end

optparse.parse!

if !options[:user] || !options[:pass] || !options[:base_uri]
  STDERR.puts "Error: You have to define user, pass and base_uri"
  exit 1
end

if !options[:product_id] || !options[:quantity]
  STDERR.puts "Error: You have to specify product_id and quantity."
  exit 1
end

if options[:quantity].to_i < 1
  STDERR.puts "Error: Quantity to put in cart has to be > 0."
  exit 1
end
options[:quantity] = options[:quantity].to_i

mech = MagentoMech.from_config options
if options[:debug] == true
  mech.log_to! STDOUT
elsif options[:debug]
  mech.log_to! options[:debug]
end

return_code = 0

mech.login

if options[:amap]
  qty = mech.add_to_cart! options[:product_id], options[:quantity]
  if qty == options[:quantity].to_i
    puts "INFO: Succeeded in adding to cart"
  elsif qty > 0
    puts "INFO: #{options[:quantity]} items not available, added #{qty}."
  else
    STDERR.puts "ERROR: Something went wrong, probably product not in stock."
    return_code = 4
  end
else
  if mech.add_to_cart options[:product_id], options[:quantity]
    puts "INFO: Succeeded in adding to cart"
  else
    STDERR.puts "ERROR: Something went wrong."
    return_code = 3
  end
end

if options[:show_cart]
  puts "Current Cart Content"
  puts mech.get_cart_content.map {|c| "#{c[1]} #{c[0]}"}
end

exit return_code