#!/usr/bin/ruby
#
# $Id: review-vol 3901 2008-02-11 20:04:59Z aamine $
#
# Copyright (c) 2003-2014 Minero Aoki
#
# This program is free software.
# You can distribute or modify this program under the terms of
# the GNU LGPL, Lesser General Public License version 2.1.
# For details of the GNU LGPL, see the file "COPYING".
#

require 'pathname'

bindir = Pathname.new(__FILE__).realpath.dirname
$LOAD_PATH.unshift((bindir + '../lib').realpath)

require 'review'
require 'optparse'

include ReVIEW::TextUtils

def main
  @config = ReVIEW::Configure.values

  part_sensitive = false
  basedir = nil
  yamlfile = nil
  opts = OptionParser.new
  opts.version = ReVIEW::VERSION
  opts.on('--yaml=YAML', 'Read configurations from YAML file.') do |yaml|
    yamlfile = yaml
  end
  opts.on('-P', '--part-sensitive', 'Prints volume of each parts.') {
    part_sensitive = true
  }
  opts.on('--directory=DIR', 'Compile all chapters in DIR.') {|path|
    basedir = path
  }
  opts.on('--help', 'Print this message and quit') {
    puts opts.help
    exit 0
  }
  begin
    opts.parse!
  rescue OptionParser::ParseError => err
    $stderr.puts err.message
    $stderr.puts opts.help
    exit 1
  end

  book = basedir ? ReVIEW::Book.load(basedir) : ReVIEW::Book::Base.load
  book.config = @config
  if yamlfile
    book.load_config(yamlfile)
  end

  if part_sensitive
    sep = ""
    book.each_part do |part|
      print sep
      sep = "\n"
      puts "Part #{part.number} #{part.name}" if part.number
      part.each_chapter do |chap|
        print_chapter_volume chap
      end
      puts '    --------------------'
      print_volume part.volume
    end
  else
    book.each_chapter do |chap|
      print_chapter_volume chap
    end
  end
  puts '============================='
  print_volume book.volume #puts "Total #{book.volume}"
rescue ReVIEW::ApplicationError, Errno::ENOENT => err
  raise if $DEBUG
  $stderr.puts "#{File.basename($0)}: #{err.message}"
  exit 1
end

def print_chapter_volume(chap)
  vol = chap.volume
  title = chap.title
  printf "%s %3dKB %6dC %5dL %3dP %s %-s\n",
         chapnumstr(chap.number), vol.kbytes, vol.chars, vol.lines, vol.page,
         "#{chap.name} ".ljust(25, '.'), title
end

def print_volume(vol)
  printf "    %3dKB %6dC %5dL %3dP\n", vol.kbytes, vol.chars, vol.lines, vol.page
end

def chapnumstr(n)
  n ? sprintf('%2d.', n) : '   '
end

main
