#!/usr/bin/env ruby

require "date"
require "nom/nom"

commands = [
    # format: [ long_form, short_form, arguments, description ]
    [ "status", nil, nil, "Display a short food log" ],
    [ "weight", "w", "<weight>", "Report a weight measurement" ],
    [ "search", "s", "<term>", "Search for a food item in the web" ],
    [ "nom", "n", "<description> <energy>", "Report that you ate something" ],
    [ "yesterday", "y", "<desc.> <energy>", "Like nom, but for yesterday" ],
    [ "plot", "p", nil, "Plot a weight/intake graph" ],
    [ "log", "l", nil, "Display the full food log" ],
    [ "grep", "g", "<term>", "Search in the food log" ],
    [ "edit", "e", nil, "Edit the input file" ],
    [ "editw", "ew", nil, "Edit the weight file" ],
    [ "config", "c", nil, "Edit the config file (see below for options)" ],
    [ "help", nil, nil, "Print this help" ],
]

aliases = {
    "--help": "help",
    "-h": "help",
}

nom = Nom::Nom.new

cmd_name = (ARGV.shift or "status")

if aliases.include? cmd_name.to_sym
    cmd_name = aliases[cmd_name.to_sym]
end

command = commands.find{|c| c[0] == cmd_name or c[1] == cmd_name}

if command.nil?
    ARGV.unshift(cmd_name)
    if ARGV.last.to_f != 0
        if ARGV.size > 1
            # some words followed by a number
            cmd_name = "nom"
        else
            # a single number
            cmd_name = "weight"
        end
    else
        # some words
        cmd_name = "search"
    end

    command = commands.find{|c| c[0] == cmd_name or c[1] == cmd_name}
end

if command[0] == "help"
    puts "Available subcommands:"
    commands.each do |c|
        puts "  "+"#{c[1].to_s.rjust(2)}#{c[1] ? "," : " "} #{c[0]} #{c[2]}".ljust(32)+c[3]
    end
    puts "There are some useful defaults:"
    puts "      "+"(no arguments)".ljust(28)+"status"
    puts "      "+"<number>".ljust(28)+"weight <number>"
    puts "      "+"<term>".ljust(28)+"search <term>"
    puts "      "+"<term> <number>".ljust(28)+"nom <term> <number>"
    nom.config_usage
else
    begin
        if ARGV.empty?
            nom.send(command[0])
        else
            nom.send(command[0], ARGV)
        end
    rescue Exception => e
        puts e.backtrace
        puts e.message
        puts "Something went wrong. Usage of this command is: nom #{command[0]} #{command[2]}"
    end
end
