module OmniDataObjects
  class SourceFile
    attr_reader :name

    def initialize(name)
      @name = name
      @buffer = "/* DO NOT MODIFY: This file is autogenerated! */\n\n"
      @has_significant_content = false
    end

    @@WrittenPaths = []
    def self.written_paths
      @@WrittenPaths.dup
    end
    
    def <<(str)
      @buffer << str
      @has_significant_content = true if str.strip.length > 0
    end

    def br
      @buffer << "\n"
    end

    def write(base_dir)
      return if !@has_significant_content
    
      path = base_dir ? "#{base_dir}/#{name}" : name
      
      # This is "written" for the purposes of checking that the files we're emitting match what was expected
      @@WrittenPaths << path
      
      # Only touch the timestamp if we've modified something
      should_write = false
      if !File.exists?(path)
        STDERR.print "Writing missing #{path}...\n" if Options.debug
        should_write = true
      elsif (File.read(path) != @buffer)
        STDERR.print "Writing changed #{path}...\n" if Options.debug
        should_write = true
      end
      
      if should_write
        File.open(path, "w") do |f|
          f << @buffer
        end
      else
        STDERR.print "Not writing unchanged #{path}...\n" if Options.debug
      end
      
    end
  end
end
