module Stylish
  class MiddlemanExtension < ::Middleman::Extension
    def self.activate_stylish_extension
      ::Middleman::Extensions.register(:stylish, Stylish::MiddlemanExtension)
    end

    option :theme, String, 'The name of the theme'

    helpers do
      def stylish
        theme_root = Pathname(root).join('vendor').join extensions[:stylish].options[:theme]
        @stylish ||= Stylish::Theme.new(theme_root)
      end
    end

    def after_configuration
      @imported_stylish_images_and_fonts ||= import_stylish_images_and_fonts
    end

    def import_stylish_images_and_fonts
      environment   = app.stylish.compiler
      trusted_paths = environment.paths.select { |p| p.end_with?('images') || p.end_with?('fonts') }
      trusted_paths.each do |load_path|
        environment.each_entry(load_path) do |path|
          if path.file? && !path.basename.to_s.start_with?('_')
            logical_path = path.sub(/^#{load_path}/, '')
            environment.imported_assets << Middleman::Sprockets::ImportedAsset.new(logical_path)
          end
        end
      end
    end
  end
end