# $Id: ext_interwiki.rb,v 1.1 2004/05/09 09:24:53 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require 'qwik/ext_wikidb'

module Qwik
  class Site
    def interwiki()
      @interwiki = InterWiki.new(@config, self) if @interwiki.nil?
      @interwiki
    end
  end

  class InterWiki
    def initialize(config, site)
      @config = config
      @site = site
      @key = @config.interwiki
      @db = nil
    end

    def href(wiki, pagename)
      iw = db[wiki]
      return nil if iw.nil?
      url, encoding = iw
      pagename = pagename.u8tosjis if encoding == 'sjis'
      pagename = pagename.u8toeuc  if encoding == 'euc'
      pagename = pagename.escape
      return url.sub(/\$1/, pagename) if url.index('$1')
      url+pagename
    end

    private
    def db
      return @db if @db
      page = @site[@key]
      page = @site.create(@key) if page.nil?
      @db = page.wikidb
      @db
    end
  end

  class Plugin
    def interwiki(arg)
      wiki, pagename = arg.split(":")
      text = yield
      text = wiki+":"+pagename if text.nil?
      iw = @site.interwiki
      href = iw.href(wiki, pagename)

      if href
	e = @g.a(href){text}
	e.add_attribute('class', 'interwiki')
	return e
      else
	e = @g.span{text}
	e.add_attribute('class', 'interwiki')
	return e
      end
    end
  end
end
