#! /usr/bin/env ruby -Ku
#
# EDINET のインスタンスデータを読み込む
#  2008-01-10 katoy
#  2008-04-20 katoy
#  2008-05-03 katoy    Version = "0.1.2 (2007-05-03)"

# How to run:
#   $ ruby main.rb ../sample/X99003-000/jpfr-q2r-X99003-000-2008-09-30-01-2008-11-26.xbrl > 1.csv
#   出力結果の csv を NeoOffice などで読み込む。
#

require 'pp'
require 'optparse'
require 'xbrl'

$KCODE="utf8"

Version = "0.1.2 (2007-05-03)"  # opt.version
INDENT = "    "  # space * 4

def print_tree(fileArray, nest = 0, indent = INDENT)
  fileArray.each {|e|
    if e.class.name == "Array"
      printTree(e, nest + 1)
    else
      puts "#{indent * nest}#{e}"
    end
  }
end

class String                    # from [ruby-list:41779], for YAML bug
  def is_binary_data?
    return true if self.include?(0)
    check = self[0, 512]
    check.size < 10 * check.count("\x00-\x07\x0b\x0e-\x1a\x1c-\x1f")
  end
end

# for DEBUG
def show_info(xbrl)
  puts "==== items ===="
  puts xbrl.items.to_yaml

  puts "==== elements ===="
  puts xbrl.elements.to_yaml

  puts "==== labels ===="
  puts xbrl.labels.to_yaml

  puts "==== files ===="
  print_tree xbrl.files

  puts "==== ignore files ===="
  print_tree xbrl.ignoreFiles
end

# csv 形式で、インスタンスデータを [科目の出現順 x コンテキストの出現順] で出力する。
def my_show_table(xbrl, lang="ja")
  contexts = xbrl.contexts
  table = xbrl.get_instance_table(lang)

  title = ["", ""]
  title << contexts.keys.to_a
  puts title.join(",")

  title = ["", ""]
  title << contexts.values.to_a
  puts title.join(",")

  table.each {|k, v|
    vStr = [v[:label]]
    contexts.each {|ck, cv|
      val = v[ck]
      val = "" if val == nil
      vStr << val
    }
    puts "#{k},#{vStr.join(',')}"
  }
end

# csv 形式で、諸表を出力する。
def my_show_sheet(xbrl, lang="ja")
  contexts = xbrl.contexts
  table = xbrl.get_instance_table(lang)
  sheets = xbrl.get_edinetsheets(lang)

  sheets.each {|sheet|

    title = [sheet[:name], ""]
    title << contexts.keys.to_a
    puts title.join(",")

    title = ["", ""]
    title << contexts.values.to_a
    puts title.join(",")


    sheet[:labels].each {|row|
      id = "#{row[12]}:#{row[13]}" # prefix:name を合成する
      v = table[id]
      next if v == nil

      vStr =  [v[:label]]
      contexts.each {|ck, cv|
        val = v[ck]
        val = "" if val == nil
        vStr << val
      }

      depth = row[22].to_i - 1 # row[22]: depth
      depth = 0 if depth < 0
      vStr[0] = INDENT * depth + vStr[0]
      puts "#{id}, #{vStr.join(',')}"
    }

  }
end

#file_path = "../XBRL-CONF-CR3-2007-03-05/Common/instance/397-00-ConsistentInstance-valid.xbrl"
#file_path = "../sample/X99001-000/jpfr-asr-X99001-000-2008-03-31-01-2008-06-27.xbrl"
#file_path = "../sample/X99002-000/jpfr-q1r-X99002-000-2008-06-30-01-2008-08-08.xbrl"
#file_path = "../sample/X99003-000/jpfr-q2r-X99003-000-2008-09-30-01-2008-11-26.xbrl"
#file_path = "../sample/X99004-000/jpfr-q3r-X99004-000-2008-12-31-01-2009-02-10.xbrl"
#file_path = "../sample/X99005-000/jpfr-asr-X99005-000-2008-03-31-01-2008-06-27.xbrl"
#file_path = "../sample/X99005-001/jpfr-asr-X99005-001-2008-03-31-01-2008-06-27.xbrl"
#file_path = "../sample/X99006-000/jpfr-ssr-X99006-000-2008-09-30-02-2008-12-26.xbrl"

sheet_p = false
lang_p="ja"

ARGV.options {|opt|
  opt.banner = "\nUsage: #{$0} [options] xbrl"
  opt.on('-s', '--sheet', "output sheet form.") {|v| sheet_p = true }
  opt.on('-i', '--item', "output all instance items. (default)") {|v| sheet_p = false }
  opt.on('--lang=[en|ja]', "lang for label-name. (default=ja)") {|v| lang_p = v }
  def opt.error(msg = nil)
    $stderr.puts msg if msg
    $stderr.puts help()
    exit 1
  end

  begin
    opt.parse!
  rescue OptionParser::ParseError => err
    opt.error err.message
  end
}

exit 1 if ARGV.size == 0

file_path = ARGV.shift

xbrl = Xbrl.new
xbrl.parse_instance(file_path)

sheet_p ? my_show_sheet(xbrl, lang_p): my_show_table(xbrl, lang_p)

#--- End of File