
require 'erb'
require 'yaml'
require 'pathname'

ROOT_PATH = File.expand_path File.dirname(__FILE__)

SOURCES_PATH = File.join ROOT_PATH, '../GeoBases/DataSources/Sources.yaml'

BUILD_PATH = File.join ROOT_PATH, '.'
ASSETS_PATH = File.join ROOT_PATH, '.'

# Read YAML configuration
#File.open(SOURCES_PATH) { |f| YAML.load f }.each do |param, val|
#  Object.const_set "CONF_#{param.upcase}", val
#end
SOURCES = YAML.load File.open(SOURCES_PATH)

ASSET_FILES = {
  '_GeoBase.erb' => '_GeoBase'
}

# Config enhancements
SOURCES.each do |data, config|
    if config.nil? or config['headers'].nil?
        SOURCES[data] = { 'headers' => [] }
    end
end

SOURCES.each do |data, config|
    headers = []

    config['headers'].each do |h|
        headers << h
        if not config['subdelimiters'].nil? and
           not config['subdelimiters'][h].nil?
            headers << h + '@raw'
        end
    end
    config['headers'] = headers
end

# Special autocomplete for feed
SOURCES['feed']['headers'] = ['H0', 'H1', 'H2', 'H3']

namespace :build do

  # Compute path to the distribution tree
  def dist(*path)
    File.join BUILD_PATH, *path
  end

  # Compute path to assets
  def asset(*path)
    File.join ASSETS_PATH, *path
  end

  # Distribute asset files
  ASSET_FILES.each do |source, target|
    dist_target = dist target
    asset_source = asset source
    # Forcing
    rm dist_target
    file dist_target => asset_source do
      if asset_source =~ /\.erb$/
        puts "Realize template #{asset_source} to #{dist_target}"
        erb = ERB.new(File.read(asset_source))
        erb.filename = File.basename asset_source
        File.open(dist_target, 'w') { |f| f.write erb.result(binding) }
      else
        cp asset_source, dist_target
      end
    end
    task :realize => dist_target
  end
end

task :default => 'build:realize'
