class Window_FollowerTest < Window_Selectable
  SPACING = 64

  def initialize
    super(16, 16, 320, 448)

    @item_max = $data_actors.size - 1
    @column_max = 1

    refresh

    self.index = 0
    self.back_opacity = 230
    self.z = 9998
    self.visible = false
    self.active = false

    @fade_in = false
    @fade_out = false
  end

  def refresh
    self.contents = Bitmap.new(width - 32, row_max * SPACING)
    $data_actors.each_with_index do |actor, index|
      draw_actor(actor, index)
    end
  end

  def draw_actor(actor, index)
    return if actor.nil?
    draw_actor_name(actor, 128, (index - 1) * SPACING)
    draw_actor_graphic(actor, 64, index * SPACING - 4)
    draw_actor_id(actor, 0, (index - 1) * SPACING)
  end

  def update_cursor_rect
    super
    self.cursor_rect.height = SPACING
    y = @index / @column_max * SPACING - self.oy
    self.cursor_rect.y = y
  end

  def page_row_max
    return (self.height - 32) / SPACING
  end

  def top_row
    return self.oy / SPACING
  end

  def top_row=(row)
    super row
    self.oy = row * SPACING
  end

  def update
    super

    # Handle fade-in effect
    if @fade_in
      self.opacity += 48
      self.contents_opacity += 48
      if self.contents_opacity == 255
        @fade_in = false
      end
      return
    end

    # Handle fade-out effect
    if @fade_out
      self.opacity -= 48
      self.contents_opacity -= 48
      if self.contents_opacity == 0
        @fade_out = false
        self.visible = false
        self.active = false
      end
      return
    end

    return unless self.active

    if Input.trigger?(Input::ACTION)
      actor = $data_actors[self.index + 1] # SOMEONE PLEASE EXPLAIN TO ME WHY INDEX 0 IS NIL
      if actor.nil?
        $game_system.se_play($data_system.buzzer_se)
        return
      end

      $game_system.se_play($data_system.decision_se)
      $game_party.add_actor(actor.id)
    elsif Input.trigger?(Input::DEACTIVATE)
      actor = $data_actors[self.index + 1]
      if actor.nil?
        $game_system.se_play($data_system.buzzer_se)
        return
      end
      $game_system.se_play($data_system.cancel_se)
      $game_party.remove_actor(actor.id)
    end

    if Input.trigger?(Input::CANCEL) ||
       Input.trigger?(Input::MENU) ||
       Input.trigger?(Input::ITEMS) ||
       Input.trigger?(Input::L)
      unless Input.trigger?(Input::MENU) || Input.trigger?(Input::L)
        $game_system.se_play($data_system.cancel_se)
      end
      @fade_out = true
      return
    end
  end

  def open
    refresh

    self.opacity = 0
    self.contents_opacity = 0
    self.visible = true
    self.active = true
    @fade_in = true
  end
end
