# -*- Mode: ruby; indent-tabs-mode: nil -*-
#
#  $Id: source.rb,v 1.1 2003/09/23 01:20:40 hisa Exp $
#
#  Copyright (c) 2003 FUJIMOTO Hisakuni <hisa@fobj.com>
#
#  This program is free software.
#  You can distribute/modify this program under the terms of
#  the GNU Lesser General Public License version 2.
#
require 'rexml/document'
require 'tempura/expander'
require 'tempura/charconv'

module Tempura

  class Source

    def self.new_with_string(str, charconv = nil)
      self.new(str, charconv, false)
    end

    attr_reader :path, :charconv
    attr_accessor :name

    def initialize(str, charconv = nil, path_p = true)
      if path_p then
        @name = File.basename(str)
        @path = File.expand_path(str)
        str = File.open(@path) { |f| f.read }
      end
      @charconv = charconv || Tempura::CharConvDefault
      @document = _parse(str)
    end

    def reload
      if @path and File.exist?(@path) then
        str = File.open(@path) { |f| f.read }
        @document = _parse(str)
      end
    end

    def fetch_document
      return (@document ? @document.deep_clone : nil)
    end

    private

    def _parse(str)
      doc = REXML::Document.new( @charconv.to_u8(str) )
      @document = Tempura::Expander.pre_expand( doc, true )
    end

  end

end
