class TypingLabel
  def initialize(args, tiled_text)
    raise ArgumentError, "tiled_text is expected to be of type Tiled::MapObject::Text" unless tiled_text.class == Tiled::MapObject::Text
    @x = tiled_text.x
    @y = tiled_text.y
    @width = tiled_text.width
    @height = tiled_text.height
    @label_name = "#{tiled_text.name}#{tiled_text.id}".to_sym

    @full_text = tiled_text.to_h[:text]

    @current_text = ""

    @last_tick = 0

    @total_characters_displayed = 0
    @character_count = @full_text.length

    @text_size = 16
    @text_font = "fonts/QuinqueFive.ttf"

    @character_delay = 5

    @args = args
    __make_rt__()

  end

  def is_typing
    @total_characters_displayed < @character_count
  end

  def reset_text
    @total_characters_displayed = 0
  end

  def rect
    { x: @x, y: @y, w: @width, h: @height }
  end

  def tick args
    @args = args
    if args.state.tick_count - @last_tick > @character_delay

      @last_tick = args.state.tick_count
      if @total_characters_displayed < @character_count
        @total_characters_displayed += 1
        @current_text = @full_text.slice(0, @total_characters_displayed)
      end
    end
  end

  def to_h
    full_lines = @full_text.split("\n")
    lines = @current_text.split("\n")
    output = []
    size_enum = __calc_size_enum__
    output = lines.map_with_index do | line, index |
      line_width, line_height = $gtk.calcstringbox(full_lines[index], size_enum, @text_font)
      {
        x: (@width / 2) - (line_width / 2),
        y: @height - (@text_size * index),
        text: line,
        r: 255,
        g: 255,
        b: 255,
        font: @text_font,
        size_enum: size_enum,
        # size_px: @text_size,
        alignment_enum: 0
      }        
    end

    __make_rt__()

    @args.outputs[@label_name].borders << {x: @x + 1, y: @y + 1, w: @width - 2, h: @height - 2, r: 255, g: 0, b: 0 }
    @args.outputs[@label_name].solids << {x: @x + 1, y: @y + 1, w: @width - 2, h: @height - 2, r: 255, g: 0, b: 0 }
    @args.outputs[@label_name].labels << output

    rt_hash = {
      x: @x,
      y: @y,
      w: @width,
      h: @height,
      path: @label_name,
      primitive_marker: :sprite
    }
    rt_hash
  end


  def __calc_size_enum__
    size_enum = 0
    size_enum = -((22 - @text_size) / 2) if @text_size < 22
    size_enum = ((22 - @text_size) / 2) if @text_size >= 22
    size_enum.to_i
  end

  def __make_rt__()

    @args.outputs[@label_name].transient!
    @args.outputs[@label_name].w = @width
    @args.outputs[@label_name].h = @height
  end
end
