require 'sprockets'
require 'sprockets-sass'
require 'sass'
require 'compass'
require 'coffee-script'
require 'uglifier'

Compass.configuration do |compass|
  # ...
end

class Compiler
  attr_accessor :project_root, :asset_path, :sprockets

  def initialize(params = {})
    @project_root = File.expand_path(File.dirname(__FILE__))
    @asset_path = File.join(project_root, 'protected', 'assets')

    @sprockets = Sprockets::Environment.new(project_root) do |env|
      env.logger = Logger.new(STDOUT)

      if params[:compress]
        env.js_compressor = :uglifier
        env.css_compressor = :sass
      end
    end

    @sprockets.append_path(File.join(asset_path, 'stylesheets'))
    @sprockets.append_path(File.join(asset_path, 'javascripts'))
  end

  def compile_js
    puts "** Generating compressed js... "
    File.open(File.join(project_root, 'js', 'application.min.js'), 'w') do |f|
       f.write(sprockets.find_asset('application.js').to_s)
    end
  end

  def compile_css
    puts "** Generating compressed css... "
    File.open(File.join(project_root, 'css', 'application.min.css'), 'w') do |f|
       f.write(sprockets.find_asset('application.css').to_s)
    end
    File.open(File.join(project_root, 'css', 'pdf.min.css'), 'w') do |f|
       f.write(sprockets.find_asset('pdf.css').to_s)
    end
  end

end


namespace :assets do
  desc "Compile assets"
  task :compile do
    compiler = Compiler.new
    compiler.compile_js
    compiler.compile_css
  end

  desc "Compile javascript"
  task :compile_js do
    compiler = Compiler.new
    compiler.compile_js
  end

  desc "Compile css"
  task :compile_css do
    compiler = Compiler.new
    compiler.compile_css
  end

  desc "Compile & compress assets"
  task :compress do
    compiler = Compiler.new(:compress => true)
    compiler.compile_js
    compiler.compile_css
  end
end
