#!/usr/bin/env ruby
$LOAD_PATH << './lib'
require 'EPUBChop'
require 'trollop'

options = Trollop::options do
  version = "EPUBChop #{EPUBChop::VERSION} (c) 2013 LIBIS/KULeuven, Mehmet Celik"
  banner <<-BANNER
EPUBChop will create a preview version of an EPUB file.

Usage:
      epubchop [options] <filename>

where [options] are:
BANNER

  opt :words, "the amount of words to put in the preview", :type => :int, :default => 10
  opt :base,  "How to interprete the --words options... Possible value: percentage", :type => :string, :default => 'percentage'
  opt :line1, "Text that is shown on line 1 of the chopped pages", :type => :string, :default => 'Continue reading?'
  opt :line2, "Text that is shown on line 2 of the chopped pages", :type => :string, :default => 'Go to your local library or buy the book.'
  opt :chop, "Follow the SPINE or the NCX of the ePub", :type => :string, :default => 'spine'
  opt :verbose, "more loging true/false", :type => :boolean, :default => false
end

Trollop::die "need an EPUB file name" if ARGV.empty?


begin
    filename = File.expand_path(ARGV[0])
    words = options[:words]
    base  = options[:base]
    text  = []
    text << options[:line1] if options.has_key?(:line1)
    text << options[:line2] if options.has_key?(:line2)
    chop_by = options[:chop]
    verbose = options[:verbose]

    puts "loading EPUB #{filename}"
    b=EPUBChop.get(filename, :chop_by => chop_by.to_sym, :verbose => verbose)
    puts 'chopping EPUB'
    c=b.chop({:base => base.to_s, :words => words, :text => text})
    puts 'rebuilding EPUB'
    FileUtils.move(c, "chopped_#{File.basename(filename)}")

rescue Exception => e
  puts "An error occured\n#{e.message}"
  exit 1
end