#===============================================================================
# Para guardar los datos en PokemonGlobalMetadata
#===============================================================================
class PokemonGlobalMetadata
  attr_accessor :character_profiles
  attr_accessor :unlocked_characters

  alias characterData_initialize initialize
  def initialize
    characterData_initialize
    @character_profiles ||= {}
    @unlocked_characters ||= []
  end
end

def clUnlockCharacter(symbol,silent=false)
  $PokemonGlobal.unlocked_characters ||= [] if !$PokemonGlobal.unlocked_characters
  unless $PokemonGlobal.unlocked_characters.include?(symbol)
    $PokemonGlobal.unlocked_characters << symbol
    clProfileUpdate(_INTL("Nuevo perfil de personaje.")) unless silent
  else
    clProfileUpdate("Personaje #{symbol} ya desbloqueado.") if $DEBUG
  end
end

def clCharacterUnlocked?(symbol)
  $PokemonGlobal.unlocked_characters ||= [] if !$PokemonGlobal.unlocked_characters
  return true if $PokemonGlobal.unlocked_characters.include?(symbol)
  return false
end

def clUnlockedCharacters
  $PokemonGlobal.unlocked_characters ||= [] if !$PokemonGlobal.unlocked_characters
  array = []
  $PokemonGlobal.unlocked_characters.each do |char|
    character_profile = clGetProfile(char) rescue nil
    next unless character_profile  # Continua si no encuentra datos de perfil
    charname = character_profile.name
    charsprite = character_profile.charsprite
    event = character_profile.event
    array.push([charname, char, charsprite, event])
  end
  return array
end

#===============================================================================
# Gestionar y actualizar la información del personaje.
#===============================================================================
class CharacterProfile
  attr_accessor :id, :name, :fullname, :age, :gender, :hometown, :event, :ally
  attr_accessor :partner, :charsprite, :trainerclass, :description, :data

  def initialize(profile_data)
    @id           = profile_data[:ID]
    @name         = profile_data[:Name]
    @fullname     = profile_data[:NameFull]     || @name
    @age          = profile_data[:Age]          || "Desconocida"
    @gender       = profile_data[:Gender]       || "Desconocido"
    @hometown     = profile_data[:Hometown]     || "Desconocido"
    @description  = profile_data[:Description]  || "Sin descripción disponible"
    @charsprite   = profile_data[:Charsprite]   || nil
    @partner      = profile_data[:Partner]      || nil
    @trainerclass = profile_data[:TrainerClass] || nil
    @event        = profile_data[:CommonEvent]  || nil
    @ally         = profile_data[:AllyStatus]   || 0
        
    # Datos desbloqueables
    @data = {
      1 => [profile_data[:Data1_1], profile_data[:Data1_2]],
      2 => [profile_data[:Data2_1], profile_data[:Data2_2]],
      3 => [profile_data[:Data3_1], profile_data[:Data3_2]]
    }

    $PokemonGlobal.character_profiles ||= {}
    $PokemonGlobal.character_profiles[@id] ||= {
      :name => @name,
      :fullname => @fullname,
      :age => @age,
      :partner => @partner,
      :description => @description,
      :gender => @gender,
      :hometown => @hometown,   
      :charsprite => @charsprite,
      :ally => @ally,
      :unlocks => profile_data[:InitialUnlocks] || {1 => 0, 2 => 0, 3 => 0}
    }
    
    @unlocked_data = $PokemonGlobal.character_profiles[@id][:unlocks]
  end

  # Método para desbloquear un dato específico y guardarlo en $PokemonGlobal
  def unlock_data(index, version)
    if @data[index] && (version == 1 || version == 2)
      @unlocked_data[index] = version
      $PokemonGlobal.character_profiles[@id][:unlocks] = @unlocked_data
    else
      puts "Dato no encontrado o versión inválida"
    end
  end

  # Método para obtener el dato actual desbloqueado
  def get_data(index)
    version = @unlocked_data[index]
    return version && version > 0 ? @data[index][version - 1] : "Dato no disponible"
  end

  def update_name(name)
    $PokemonGlobal.character_profiles[@id][:name] = name
  end
  
  def update_fullname(name)
    $PokemonGlobal.character_profiles[@id][:fullname] = name
  end
  
  def update_hometown(town)
    $PokemonGlobal.character_profiles[@id][:hometown] = hometown
  end
  
  def update_gender(gender)
    $PokemonGlobal.character_profiles[@id][:gender] = gender
  end
  
  def update_age(age)
    $PokemonGlobal.character_profiles[@id][:age] = age
  end
  
  def update_partner(poke)
    $PokemonGlobal.character_profiles[@id][:partner] = poke
  end

  def update_sprite(sprite)
    $PokemonGlobal.character_profiles[@id][:charsprite] = sprite
  end
  
  def update_description(description)
    $PokemonGlobal.character_profiles[@id][:description] = description
  end
  
  def update_alliance(isally)
    $PokemonGlobal.character_profiles[@id][:ally] = isally
  end
  
end

#===============================================================================
# Utilidades para actualizar los datos
#===============================================================================
  def clGetProfile(id=nil)
    profile_data = CharacterProfilesData.const_get(id) rescue nil
    if profile_data
      character_profile = CharacterProfile.new(profile_data)
      if $PokemonGlobal.character_profiles[character_profile.id]
        character_profile.age         = $PokemonGlobal.character_profiles[character_profile.id][:age]
        character_profile.partner     = $PokemonGlobal.character_profiles[character_profile.id][:partner]
        character_profile.description = $PokemonGlobal.character_profiles[character_profile.id][:description]
        character_profile.name        = $PokemonGlobal.character_profiles[character_profile.id][:name]
        character_profile.fullname    = $PokemonGlobal.character_profiles[character_profile.id][:fullname]
        character_profile.gender      = $PokemonGlobal.character_profiles[character_profile.id][:gender]
        character_profile.hometown    = $PokemonGlobal.character_profiles[character_profile.id][:hometown]
        character_profile.charsprite  = $PokemonGlobal.character_profiles[character_profile.id][:charsprite]
        character_profile.ally        = $PokemonGlobal.character_profiles[character_profile.id][:ally]
      end
      return character_profile
    end
    return nil
  end

  def clUpdateData(id,dato,version,silent=false)
    character_profile = clGetProfile(id)
    if character_profile
      character_profile.unlock_data(dato, version)
      clProfileUpdate(_INTL("Perfil de personaje actualizado")) unless silent
    end
  end
  
  def clUpdateAge(id,age)
    character_profile = clGetProfile(id)
    character_profile.update_age(age) if character_profile 
  end
  
  def clUpdatePartner(id,poke)
    character_profile = clGetProfile(id)
    character_profile.update_partner(poke) if character_profile 
  end
  
  def clUpdateDesc(id,desc)
    character_profile = clGetProfile(id)
    character_profile.update_description(desc) if character_profile 
  end

  def clUpdateName(id,name)
    character_profile = clGetProfile(id)
    character_profile.update_name(name) if character_profile 
  end
  
  def clUpdateFullname(id,name)
    character_profile = clGetProfile(id)
    character_profile.update_fullname(name) if character_profile 
  end
  
  def clUpdateHometown(id,town)
    character_profile = clGetProfile(id)
    character_profile.update_hometown(town) if character_profile 
  end
  
  def clUpdateGender(id,gender)
    character_profile = clGetProfile(id)
    character_profile.update_gender(gender) if character_profile 
  end
    
  def clUpdateSprite(id,sprite)
    character_profile = clGetProfile(id)
    character_profile.update_sprite(sprite) if character_profile 
  end
  
  def clUpdateAlliance(id,ally)
    character_profile = clGetProfile(id)
    character_profile.update_alliance(ally) if character_profile 
  end
  
#===============================================================================
# Utilidades para obtener cada dato
#===============================================================================
  def clGetPokemonPartner(pokemon)
    return if !pokemon
    pokemon = getID(PBSpecies,pokemon) if pokemon.is_a?(String) || pokemon.is_a?(Symbol)
    return pokemon if pokemon.is_a?(Numeric)
    return nil
  end
    
  def clGetTrainerClass(trainerid)
    if trainerid.is_a?(String) || trainerid.is_a?(Symbol)
      if !hasConst?(PBTrainers,trainerid)
        p _INTL("El tipo de entrenador no existe ({1}, {2}, ID {3})",trainerid,trainername,partyid)
        return nil
      else
        trainerid=getID(PBTrainers,trainerid)
      end
    end
    return trainerid if trainerid 
  end
  
  def clProfileUpdate(string)
  if !defined?(UISprite)
    Kernel.pbMessage(_INTL("{1}",string))
  else
    bitmap = Bitmap.new(Graphics.width, 50)
    pbSetSystemFont(bitmap)
    base = Color.new(248,248,248)
    shadow = Color.new(48,48,48)
    pbSetSmallFont(bitmap)
    textpos = [[_INTL("{1}",string),10,15,0,base,shadow]]
    pbDrawTextPositions(bitmap,textpos)
    $scene.addSprite(-bitmap.width,16,bitmap)
    return true
  end
end


  
#===============================================================================
# Utilidades DEBUG
#===============================================================================
def clUnlockAllCharacters
  $PokemonGlobal.unlocked_characters ||= []
  CharacterProfilesData.constants.each do |character_symbol|
    unless $PokemonGlobal.unlocked_characters.include?(character_symbol)
      $PokemonGlobal.unlocked_characters << character_symbol
    end
  end
  p "Todos los personajes han sido desbloqueados."
end
