#!/usr/bin/ruby -w
# Encoding: UTF-8
# frozen_string_literal: true
# =========================================================================== #
module PDFWalker

class Walker < Window

  private

  # ========================================================================= #
  # === create_objectview
  # ========================================================================= #
  def create_objectview
    @objectview = ObjectView.new(self)
  end

  class ObjectView < Notebook

    attr_reader :parent
    attr_reader :pdfpanel, :valuepanel

    # ======================================================================= #
    # === initialize
    # ======================================================================= #
    def initialize(parent)
      @parent = parent
      super()

      @pdfbuffer = TextBuffer.new
      @pdfview = TextView.new(@pdfbuffer).
                 set_editable(false).
                 set_cursor_visible(false).
                 set_left_margin(5)

      @pdfpanel = ScrolledWindow.new.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
      @pdfpanel.add_with_viewport @pdfview
      append_page(
        @pdfpanel, Label.new('PDF Code')
      )

      @pdfbuffer.create_tag('Default',
        weight: Pango::Weight::BOLD,
        family: 'monospace#,
        scale: Pango::Scale::LARGE
      )
    end

    # === load
    def load(object)
      begin
        self.clear

        case object
        when Origami::PDF::Header, Origami::FDF::Header, Origami::PPKLite::Header
          text = object.to_s
          @pdfbuffer.set_text(text)
          @pdfbuffer.apply_tag("Default", @pdfbuffer.start_iter, @pdfbuffer.end_iter)

        when Origami::Object
          if object.is_a?(Origami::Stream)
            text = [ "#{object.no} #{object.generation} obj", object.dictionary ].join($/)
          else
            text = object.to_s
          end
          # text.encode!(
          #   'UTF-8', { replace: '.' }
          # )
          # text.tr!(
          #   "\x00", '.'
          # )
          @pdfbuffer.set_text(text)
          @pdfbuffer.apply_tag('Default', @pdfbuffer.start_iter, @pdfbuffer.end_iter)
        end
      rescue
        @parent.error("An error occured while loading this object.\n#{$!} (#{$!.class})")
      end
    end

    # === clear
    def clear
      @pdfbuffer.set_text('')
    end
  end

end; end