local bible = SILE.require("bible", "classes")
local interlinear = bible { id = "interlinear" }
local insertions = SILE.require("packages/insertions")
SILE.languageSupport.loadLanguage("ja")

interlinear:loadPackage("masters")
interlinear:loadPackage("ruby")
interlinear:defineMaster({
    id = "right",
    firstContentFrame = "content",
    frames = {
      content = {
        left = "8.3%pw",
        right = "86%pw",
        top = "11.6%ph",
        bottom = "top(translation)"
      },
      folio = {
        left = "left(content)",
        right = "right(content)",
        top = "bottom(footnotes)+3%ph",
        bottom = "bottom(footnotes)+5%ph"
      },
      runningHead = {
        left = "left(content)",
        right = "right(content)",
        top = "top(content)-8%ph",
        bottom = "top(content)-3%ph"
      },
      translation = {
        left = "left(content)",
        right = "right(content)",
        height = "0",
        bottom = "top(footnotes)",
      },
      footnotes = {
        left = "left(content)",
        right = "right(content)",
        height = "0",
        bottom = "83.3%ph"
      }
    }
  })

interlinear:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" })

interlinear:loadPackage("tableofcontents")

if not SILE.scratch.headers then SILE.scratch.headers = {} end

interlinear.init = function (self)
  interlinear:mirrorMaster("right", "left")
  interlinear.pageTemplate = SILE.scratch.masters["right"]
  self:loadPackage("chapterverse")
  interlinear:loadPackage("footnotes", { insertInto = "footnotes", stealFrom = { "content" } })
  insertions.exports:initInsertionClass("translation", {
    insertInto = "translation",
    stealFrom = { "content" },
    maxHeight = SILE.length.new({length = SILE.toPoints("75", "%ph") }),
    topBox = SILE.nodefactory.newVglue({height = SILE.length.parse("2ex") }),
    interInsertionSkip = SILE.length.parse("1ex"),
  })
  return plain.init(self)
end

SILE.registerCommand("translation", function(options, content)
  local opts = SILE.scratch.insertions.classes.translation
  local f = SILE.getFrame("translation")
  local oldT = SILE.typesetter
  SILE.typesetter = SILE.typesetter {}
  SILE.typesetter:init(f)
  SILE.typesetter.pageTarget = function () return 0xFFFFFF end
  SILE.settings.pushState()
  SILE.settings.reset()
  local material = SILE.Commands["vbox"]({}, function()
    SILE.Commands["translation:font"]({}, function()
    --  SILE.call("translation:atstart", options)
    --  SILE.call("translation:counter", options)
      SILE.typesetter:typeset(SILE.scratch.chapterverse.verse)
      SILE.typesetter:typeset(" ")
      SILE.process(content)
    end)
  end)
  SILE.settings.popState()
  SILE.typesetter = oldT
  insertions.exports:insert("translation", material)
  -- SILE.scratch.counters.translation.value = SILE.scratch.counters.translation.value + 1
end)

return interlinear
