
# 2009-03-14 katoy

# EDINET での ロール一覧は次を参照すること。
# http://www.fsa.go.jp/search/20090309/tguideapdx20090309.xls
#    企業別タクソノミ作成ガイドライン  添付資料〕（EXCEL)

require 'rubygems'
require 'xml/libxml'
require 'pp'
require 'benchmark'

NS_LINK ='http://www.xbrl.org/2003/linkbase'

def add_labels(doc, info)

  add_labellinks(doc.root.find('link:labelLink/*').last, info)
  doc
end

def add_labellinks(to, info)

  locator = XML::Node.new('link:loc')
  locator['xlink:type'] = 'locator'
  locator['xlink:href'] = info[:from_href]
  locator['xlink:label'] = info[:from]
  locator['xlink:title'] = info[:from]
  locator['xlink:id'] = info[:from]

  to << locator

  info[:to].each do |toInfo|

    if (to[:to_text] != nil)
      # 文字列を指定して、追加する場合
      label = XML::Node.new('link:label')
      label['xml:lang']= 'ja'
      label['xlink:type'] = 'resource'
      label['xlink:role']= toInfo[:role]
      label['xlink:label']= toInfo[:to]
      label['xlink:title']= toInfo[:to]
      label['xlink:id']=toInfo[:to]
      label << XML::Node.new_text(toInfo[:text])
      to << label
    elsif
      # 既存のラベルを流用して、追加する場合
      label_loc = XML::Node.new('link:loc')
      label_loc['xlink:type'] = 'locator'
      label_loc['xlink:href'] = toInfo[:to_href]
      label_loc['xlink:label'] = toInfo[:to]
      label_loc['xlink:title'] = toInfo[:to]
      label_loc['xlink:id'] = toInfo[:to]
      to << label_loc
    end

    arc = XML::Node.new('link:labelArc')
    arc['xlink:type'] = 'arc'
    arc['xlink:arcrole'] = 'http://www.xbrl.org/2003/arcrole/concept-label'
    arc['xlink:from'] = info[:from]
    arc['xlink:to'] = toInfo[:to]
    # arc['xlink:label'] = ''
    # arc['xlink:id'] = ''
    # arc['xlink:order'] = '1'
    to << arc
  end

end

if $0 == __FILE__

  xml = "../data/td-net/081220090203088072/tdnet-qcedjpfr-33500-2008-11-30-01-2009-02-20-label.xml"

  # xml = ARGV[0]

  puts Benchmark.measure {

    doc = XML::Document.file(xml)

    # 文字列を指定して、追加する場合
    #info = {
    #  :from => 'jpfr-t-cte_CurrentLiabilitiesAbstract',
    #  :from_href => 'http://info.edinet-fsa.go.jp/jp/fr/gaap/t/cte/2009-03-09/jpfr-t-cte-2009-03-09.xsd#jpfr-t-cte_CurrentLiabilitiesAbstract',
    #  :to => [{:to => "TO", :role => "ROLE", :text => "TEXT"}]
    #}

    # 既存のラベルを流用して、追加する場合
    info = {
      :from => 'jpfr-t-cte_CurrentLiabilitiesAbstract',
      :from_href => 'http://info.edinet-fsa.go.jp/jp/fr/gaap/t/cte/2009-03-09/jpfr-t-cte-2009-03-09.xsd#jpfr-t-cte_CurrentLiabilitiesAbstract',
      :to => [{:to => "label_BuildingsNet",
          :role => "ROLE",
          :to_href => 'http://info.edinet-fsa.go.jp/jp/fr/gaap/t/cte/2009-03-09/jpfr-t-bnk-2009-03-09-label.xml#label_BuildingsNet'}]
    }

    doc = add_labels(doc, info)

    puts doc.to_s
  }

end
