#!/usr/bin/ruby
#
# Copyright (c) 2014-2017 Minero Aoki, Kenshi Muto
#               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
  @logger = ReVIEW.logger
  @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.') { |yaml| yamlfile = yaml }
  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') do
    puts opts.help
    exit 0
  end
  begin
    opts.parse!
  rescue OptionParser::ParseError => err
    @logger.error err.message
    $stderr.puts opts.help
    exit 1
  end

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

  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 { |chap| print_chapter_volume chap }
      puts '    --------------------'
      print_volume part.volume
    end
  else
    book.each_chapter { |chap| print_chapter_volume chap }
  end
  puts '============================='
  print_volume book.volume # puts "Total #{book.volume}"
rescue ReVIEW::ApplicationError, Errno::ENOENT => err
  raise if $DEBUG
  @logger.error "#{File.basename($PROGRAM_NAME)}: #{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
