# $Id: interwiki.rb,v 1.7 2004/04/22 14:47:49 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.

# refer: hiki/interwiki.rb by TAKEUCHI Hitoshi
# Copyright (C) 2002-2003 TAKEUCHI Hitoshi <hitoshi@namaraii.com>

module Qwik
  class InterWiki
    def initialize(site)
      @site = site
      @wikis = {}
#      @key = @config.interwiki
      @key = "InterWikiName"
      load_names
    end

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

    private
    URL  = '(?:http|https|ftp|mailto|file):[a-zA-Z0-9;/?:@&=+$,\-_.!~*\'()#%]+'
    NAME_RE =  /\[\[([^|]+)\|(#{URL})\]\](?:\s+(sjis|euc|alias))?/
    def load_names
      @site[@key].load.scan(NAME_RE) {|i|
        e = 2 < i.size ? i[2] : 'none'
        @wikis[i[0]] = {:url => i[1], :encoding => e}
      }
    end
  end
end
