#===============================================================================
# Redistribuidor de EV'S
# Creado por Clara. Compatibilidad con Essentials BES
# Permite mover los ev's que ya posee el pokémon a otra posición.
# El coste va aumentando a mas puntos añades a un stat(de base los que ya tiene actualmente)
# Pretende ser un "clon" de la pantalla de datos de los pokémon, si quieres editar esa parte, 
# Ve a ``def drawPokeData``
#===============================================================================

class EVReorganizeScene
  ######## CONFIGURACIÓN ########
  
  COST_DIFFERENCE = 500
  
  BASECOLOR_LIGHT   = Color.new(248,248,248)
  SHADOWCOLOR_LIGHT = Color.new(47,46,54)
  
  BASECOLOR_DARK   = Color.new(64,64,64)
  SHADOWCOLOR_DARK = Color.new(176,176,176)
  
  ###############################
  def initialize(pokemon)
    @pokemon = pokemon
    @original_evs = Array.new(6) { |i| pokemon.ev[i] }
    @ivs = Array.new(6) { |i| pokemon.iv[i] }
    @current_evs = @original_evs.clone
    @max_evs = @original_evs.inject(0) { |sum, ev| sum + ev }
    @cost_per_change = COST_DIFFERENCE
    @selected_stat = 0

    @base=BASECOLOR_LIGHT
    @shadow=SHADOWCOLOR_LIGHT
 
    @base2=BASECOLOR_DARK
    @shadow2=SHADOWCOLOR_DARK
  end

  def pbPokerus(pkmn)
    return pkmn.pokerusStage
  end
  
  def pbStartScene
    
    @viewport = Viewport.new(0, 0, Graphics.width, Graphics.height)
    @viewport.z = 99999
    @sprites = {}

    addBackgroundPlane(@sprites,"bg","EVRedirector/bg",@viewport)
    addBackgroundPlane(@sprites,"background","EVRedirector/page",@viewport)

    @sprites["overlay"] = BitmapSprite.new(Graphics.width, Graphics.height, @viewport)
    @overlay = @sprites["overlay"].bitmap
    @sprites["overlay2"] = BitmapSprite.new(Graphics.width, Graphics.height, @viewport)
    @overlay2 = @sprites["overlay2"].bitmap

    drawPokeData
    drawScreen
    
    pbFadeInAndShow(@sprites) { pbUpdate }
  end
  
  def drawPokeData
    @sprites["pokemon"]=PokemonSprite.new(@viewport)
    @sprites["pokemon"].setPokemonBitmap(@pokemon)
    @sprites["pokemon"].tone=TERATONES[@pokemon.teratype] if @pokemon.isTera?
    @sprites["pokemon"].mirror=false
    @sprites["pokemon"].color=Color.new(0,0,0,0)
    pbPositionPokemonSprite(@sprites["pokemon"],40,144)
    
    imagepos = []
    textpos = []
    
    pbSetSystemFont(@overlay)
    
    if pbPokerus(@pokemon)==1 || @pokemon.hp==0 || @pokemon.status>0
      status=6 if pbPokerus(@pokemon)==1
      status=@pokemon.status-1 if @pokemon.status>0
      status=5 if @pokemon.hp==0
      imagepos.push(["Graphics/Pictures/statuses",124,100,0,16*status,44,16])
    end
    if @pokemon.isShiny?
      imagepos.push([sprintf("Graphics/Pictures/shiny"),2,134,0,0,-1,-1])
    end
    if pbPokerus(@pokemon)==2
      imagepos.push([sprintf("Graphics/#{SUMMARY_ROUTE}/summaryPokerus"),176,100,0,0,-1,-1])
    end
    ballused=@pokemon.ballused ? @pokemon.ballused : 0
    ballimage=sprintf("Graphics/#{SUMMARY_ROUTE}/summaryball%02d",@pokemon.ballused)
    imagepos.push([ballimage,14,60,0,0,-1,-1])
    if (@pokemon.isShadow? rescue false)
      imagepos.push(["Graphics/#{SUMMARY_ROUTE}/summaryShadow",224,240,0,0,-1,-1])
      shadowfract=@pokemon.heartgauge*1.0/PokeBattle_Pokemon::HEARTGAUGESIZE
      imagepos.push(["Graphics/#{SUMMARY_ROUTE}/summaryShadowBar",242,280,0,0,(shadowfract*248).floor,-1])
    end
    textpos=[
       [_INTL("DATOS"),26,16,0,@base,@shadow],
       [@pokemon.name,46,62,0,@base,@shadow],
       [@pokemon.level.to_s,46,92,0,@base2,@shadow2],
       [_INTL("Objeto"),16,320,0,@base,@shadow],
    ]
    
    if @pokemon.hasItem?
      textpos.push([PBItems.getName(@pokemon.item),16,352,0,@base2,@shadow2])
    else
      textpos.push([_INTL("Ninguno"),16,352,0,Color.new(184,184,160),Color.new(208,208,200)])
    end
    
    pbDrawTextPositions(@overlay, textpos)
    pbDrawImagePositions(@overlay, imagepos)
  end
  
  
  def pbUpdate
    pbUpdateSpriteHash(@sprites)
  end
  
  STAT_ORDER = [0, 1, 2, 4, 5, 3]
  
  def drawScreen
    @overlay.clear
    drawPokeData
    textpos = []
    imagepos = []
    statshadows=[]
    # Identificar los dos stats más altos
    top_stats = getTopTwoStats

    # Dibujar nombres y valores de stats
    stats = [@pokemon.totalhp, @pokemon.attack, @pokemon.defense,
             @pokemon.speed, @pokemon.spatk, @pokemon.spdef] # Recalcular valores actualizados

    STAT_ORDER.each_with_index do |stat_index, i|
      # Naturaleza
      statshadows[i]=@shadow
      if !(@pokemon.isShadow? rescue false) || @pokemon.heartStage<=3
        natup=(@pokemon.nature/5).floor
        natdn=(@pokemon.nature%5).floor
        statshadows[natup]=Color.new(170,50,33) if natup!=natdn
        statshadows[natdn]=Color.new(0,95,209) if natup!=natdn
      end
    end  
    STAT_ORDER.each_with_index do |stat_index, i|
      
      y = 88 + i * 32
      textpos.push([PBStats.getName(stat_index, true), 234, y, 0, @base, statshadows[stat_index] ])
      textpos.push([stats[stat_index].to_s, 366, y, 2, @base2, @shadow2])
      textpos.push([@current_evs[stat_index].to_s, 424, y, 2, @base2, @shadow2])
      textpos.push([@ivs[stat_index].to_s, 476, y, 2, @base2, @shadow2])

      @arrowbitmap = AnimatedBitmap.new("Graphics/Pictures/EVRedirector/arrow_mini")
      rectsize = 32
      @overlay.blt(422-rectsize-8, y, @arrowbitmap.bitmap, Rect.new(0, 0, rectsize, rectsize))
      @overlay.blt(422+12, y, @arrowbitmap.bitmap, Rect.new(rectsize, 0, rectsize, rectsize))

      # Marcar con imagen si es uno de los stats más altos
      if top_stats.include?(stat_index)
        imagepos.push(["Graphics/Pictures/EVRedirector/recomended", 330, y + 8, 0, 0, -1, -1])
      end

      # Selector
      if i == @selected_stat
        imagepos.push(["Graphics/Pictures/EVRedirector/selector", 224, y, 0, 0, -1, -1])
      end
    end

    # EVs totales y restantes
    total_evs = @current_evs.inject(0) { |sum, ev| sum + ev }
    remaining_evs = @max_evs - total_evs
    textpos.push(["EV's Totales: #{total_evs}/#{@max_evs}", 234, 286, false, @base2, @shadow2])
    textpos.push(["EV's Restantes: #{remaining_evs}", 234, 318, false, @base2, @shadow2])

    # Coste
    cost = calculateCost
    cost_color = cost > $Trainer.money ? Color.new(255, 0, 0) : @base2
    textpos.push(["Coste: #{cost}$", 234, 350, false, cost_color, @shadow2])

    # Confirmar botón
    confirm_color = @selected_stat == 6 ? Color.new(0, 255, 0) : @base2
    textpos.push(["Confirmar", 400, 350, false, confirm_color, @shadow2])

    if @selected_stat == 6
      imagepos.push(["Graphics/Pictures/EVRedirector/selectorS", 384, 350, 0, 0, -1, -1])
    end
    
    
    pbDrawTextPositions(@overlay, textpos)
    pbDrawImagePositions(@overlay, imagepos)
  end
  
  
  
  def pbScene
    loop do
      Graphics.update
      Input.update
      pbUpdate

      # Cálculo de EVs restantes y validación
      total_evs = @current_evs.inject(0) { |sum, ev| sum + ev }
      remaining_evs = @max_evs - total_evs

      # Navegación de estadísticas
      if Input.trigger?(Input::UP)
        @selected_stat = (@selected_stat - 1) % 7
      elsif Input.trigger?(Input::DOWN)
        @selected_stat = (@selected_stat + 1) % 7
      end

      # Modificación de EVs
      if @selected_stat < 6
        stat_index = STAT_ORDER[@selected_stat]
        if Input.repeat?(Input::LEFT)
          modifyEvs(stat_index, -1) if @current_evs[stat_index] > 0
        elsif Input.repeat?(Input::RIGHT)
          modifyEvs(stat_index, 1) if @current_evs[stat_index] < 252 && remaining_evs > 0
        elsif Input.trigger?(Input::L)
          modifyEvs(stat_index, -@current_evs[stat_index]) # Quitar todos los EVs
        elsif Input.trigger?(Input::R)
          max_addable = [252 - @current_evs[stat_index], remaining_evs].min
          modifyEvs(stat_index, max_addable) # Añadir todos los EVs posibles
        end
      end

      # Confirmación de cambios
      if Input.trigger?(Input::C) && @selected_stat == 6
        cost = calculateCost
        if cost <= $Trainer.money
          if Kernel.pbConfirmMessage(_INTL("¿Confirmar cambios?"))
            applyChanges(cost)
            Kernel.pbMessage("Los EVs fueron reorganizados con éxito.")
            break
          end
        else
          Kernel.pbMessage("No tienes suficiente dinero.")
        end
      end

      # Cancelación de cambios
      if Input.trigger?(Input::B)
        if Kernel.pbConfirmMessage("¿Cancelar la reorganización?")
          revertChanges
          break
        end
      end

      drawScreen
    end
  end

  def modifyEvs(stat, change)
    @current_evs[stat] += change
    @pokemon.ev[stat] = @current_evs[stat]
    @pokemon.calcStats
    pbSEPlay("GUI sel cursor")
  end
  
  def applyChanges(cost)
    $Trainer.money -= cost
    6.times { |i| @pokemon.ev[i] = @current_evs[i] }
    @pokemon.calcStats
    pbSEPlay("SlotsCoin")
  end
  
  def revertChanges
    @current_evs = @original_evs.clone
    6.times { |i| @pokemon.ev[i] = @original_evs[i] }
    @pokemon.calcStats
  end
  
  def calculateCost
    cost = 0
    6.times do |i|
      change = @current_evs[i] - @original_evs[i]
      cost += change * @cost_per_change if change > 0
    end
    return cost
  end

  def getTopTwoStats
    stats = @pokemon.baseStats.each_with_index.sort.reverse
    return stats[0..1].map { |s| s[1] }
  end
  
  def pbEndScene
    pbFadeOutAndHide(@sprites) { pbUpdate }
    pbDisposeSpriteHash(@sprites)
    @viewport.dispose
  end
  
end

class EVReorganize
  def initialize(scene)
    @scene = scene
  end
  
  def pbStartScreen
    @scene.pbStartScene
    ret=@scene.pbScene
    @scene.pbEndScene
    return ret
  end
  
end

def pbReorganizeEVs(pokemon)
  pbFadeOutIn {
    scene = EVReorganizeScene.new(pokemon)
    screen = EVReorganize.new(scene)
    screen.pbStartScreen
  }
end
