# # Copyright © 2013 # Nathan Currier # # Use, modification, and distribution are all subject to the # Boost Software License, Version 1.0. (See the accompanying # file LICENSE.md or at rideliner.tk/LICENSE.html). # # <description> #

module Bakery

module Ingredient
  class File < File
    include Dispatcher

    def toBlockCommentLine line
      "#{line.empty? ? '' : ' '}#{line}"
    end

    # TODO try cleaning this up...
    def insertCopyrightNotice
      Bakery[:copyright].each { |line|
        if line.is_a? Proc
          lines = line.call
          if lines.is_a? Array
            lines.each { |called_line|
              puts toBlockCommentLine called_line
            }
          else
            puts toBlockCommentLine lines
          end
        else
          puts toBlockCommentLine line
        end
      }
    end

    def initialize filename, *args, &block
      already_exists = File.exist? filename

      if !already_exists || args.include?(:always_overwrite)
        if !already_exists
          Bakery::Log.info "#{self.class} creating: #{filename}"
        else
          Bakery::Log.info "#{self.class} overwriting: #{filename}"
        end

        super filename, 'w+'

        dispatch &block
      else
        super filename, 'a+'

        if args.include?(:always_append)
          Bakery::Log.info "#{self.class} appending: #{filename}"

          dispatch &block
        else
          Bakery::Log.info "#{self.class} opening: #{filename}"
        end
      end
    end

    def from filename
      ICING_SEARCH.search(filename) { |file|
        Bakery::Log.info "copying '#{file}' to '#{path}'"

        FileUtils.cp file, path
      }
    end
  end
end

end