require 'rake'
require 'rake/packagetask'

MAPSTER_VERSION  = "unknown"

MAPSTER_ROOT = File.expand_path(File.dirname(__FILE__))
MAPSTER_SRC  = File.join(MAPSTER_ROOT, '../src')
MAPSTER_DIST = File.join(MAPSTER_ROOT, '../dist')
MAPSTER_PKG = File.join(MAPSTER_ROOT, '../pkg')

MAPSTER_COMPONENTS = [
  'license',
  'redist/when',
  'core',
  'graphics',
  'mapimage',
  'mapdata',
  'areadata',
  'areacorners',
  'scale',
  'tooltip'
]


MAPSTER_ZEPTO_COMPONENTS = [
  'license',
  'zepto',
  'redist/when',
  'core',
  'graphics',
  'mapdata',
  'mapimage',
  'areadata',
  'areacorners',
  'scale',
  'tooltip'
]

#task :default => [:clean, :concat, :concatzepto, :dist]
task :default => [:clean, :concat, :dist]

desc "Clean the distribution directory."
task :clean do
  rm_rf MAPSTER_DIST
  mkdir MAPSTER_DIST
end

def normalize_whitespace(filename)
  contents = File.readlines(filename)
  contents.each { |line| line.sub!(/\s+$/, "") }
  File.open(filename, "w") do |file|
    file.write contents.join("\n").sub(/(\n+)?\Z/m, "\n")
  end
end

desc "Strip trailing whitespace and ensure each file ends with a newline"
task :whitespace do
  Dir["src/**/*"].each do |filename|
    normalize_whitespace(filename) if File.file?(filename)
  end
end

desc "Concatenate source files to build jquery.imagemapster.js"
task :concat, [:addons] => :whitespace do |task, args|
  # colon-separated arguments such as `concat[foo:bar:-baz]` specify
  # which components to add or exclude, depending on if it starts with "-"
  add, exclude = args[:addons].to_s.split(':').partition {|c| c !~ /^-/ }
  exclude.each {|c| c.sub!('-', '') }
  files = (MAPSTER_COMPONENTS | add) - exclude

  unless files == MAPSTER_COMPONENTS
    puts "Building jquery.imagemapster.js by including: #{files.join(', ')}"
  end

  File.open(File.join(MAPSTER_DIST, 'jquery.imagemapster.js'), 'w') do |f|
    f.puts files.map { |component|
      File.read File.join(MAPSTER_SRC, "#{component}.js")
    }
  end
end

desc "Concatenate source files to build jquery.imagemapster.zepto.js"
task :concatzepto, [:addons] => :whitespace do |task, args|
  # colon-separated arguments such as `concat[foo:bar:-baz]` specify
  # which components to add or exclude, depending on if it starts with "-"
  add, exclude = args[:addons].to_s.split(':').partition {|c| c !~ /^-/ }
  exclude.each {|c| c.sub!('-', '') }
  files = (MAPSTER_ZEPTO_COMPONENTS | add) - exclude

  unless files == MAPSTER_ZEPTO_COMPONENTS
    puts "Building jquery.imagemapster.zepto.js by including: #{files.join(', ')}"
  end

  File.open(File.join(MAPSTER_DIST, 'jquery.imagemapster.zepto.js'), 'w') do |f|
    f.puts files.map { |component|
      File.read File.join(MAPSTER_SRC, "#{component}.js")
    }
  end
end

def google_compiler(src, target)
  puts "Minifying #{src} with Google Closure Compiler..."
  `java -jar vendor/google-compiler/compiler.jar --js #{src} --summary_detail_level 3 --js_output_file #{target}`
end

def yui_compressor(src, target)
  puts "Minifying #{src} with YUI Compressor..."
  `java -jar vendor/yuicompressor/yuicompressor-2.4.2.jar #{src} -o #{target}`
end

def uglifyjs(src, target)
  begin
    require 'uglifier'
  rescue LoadError => e
    if verbose
      puts "\nYou'll need the 'uglifier' gem for minification. Just run:\n\n"
      puts "  $ gem install uglifier"
      puts "\nand you should be all set.\n\n"
      exit
    end
    return false
  end
  puts "Minifying #{src} with UglifyJS..."
  File.open(target, "w"){|f| f.puts Uglifier.new.compile(File.read(src))}
end

def process_minified(src, target)
  msize = File.size(File.join(MAPSTER_DIST,'jquery.imagemapster.min.js'))
  osize = File.size(src)

  puts "Original version: %.3fk" % (osize/1024.0)
  puts "Minified: %.3fk" % (msize/1024.0)
end

desc "Generates a minified version for distribution, using UglifyJS."
task :dist do
  src, target = File.join(MAPSTER_DIST,'jquery.imagemapster.js'), File.join(MAPSTER_DIST,'jquery.imagemapster.min.js')
  uglifyjs src, target
  #src, target = File.join(MAPSTER_DIST,'jquery.imagemapster.zepto.js'), File.join(MAPSTER_DIST,'jquery.imagemapster.zepto.min.js')
  #uglifyjs src, target
  process_minified src, target
end

desc "Generates a minified version for distribution using the Google Closure compiler."
task :googledist do
  src, target = File.join(MAPSTER_DIST,'jquery.imagemapster.js'), File.join(MAPSTER_DIST,'jquery.imagemapster.min.js')
  google_compiler src, target
  process_minified src, target
end

desc "Generates a minified version for distribution using the YUI compressor."
task :yuidist do
  src, target = File.join(MAPSTER_DIST,'jquery.imagemapster.js'), File.join(MAPSTER_DIST,'jquery.imagemapster.min.js')
  yui_compressor src, target
  process_minified src, target
end

desc "Generate docco documentation from sources."
task :docs do
  puts "Generating docs..."
  puts "Note: to work, install node.js first, then install docco with 'sudo npm install docco -g'."
  puts `docco src/*`
end

Rake::PackageTask.new('mapster', MAPSTER_VERSION) do |package|
  package.need_tar_gz = true
  package.need_zip = true
  package.package_dir = MAPSTER_PKG
  package.package_files.include(
    'README.md',
    'dist/**/*',
    'src/**/*',
    'test/**/*',
    'examples/**/*'
  )
end
