package org.academiadecodigo.bootcamp11.pokemon.trainer;

import org.academiadecodigo.bootcamp11.pokemon.pokemon.Pokemon;

/**
 * Each Trainer has a name and 6 pokeBalls.
 * Each pokeBall can store one Pokemon.
 * Each Trainer knows how to catch a Pokemon and how to fight another Trainer.
 */

public abstract class Trainer {
    private String name;
    private Pokemon[] pokeballs;

    public Trainer(String name) {
        this.name = name;
        this.pokeballs = new Pokemon[6];
    }

    public Trainer(String name, Pokemon[] pokemons) {
        this.name = name;
        this.pokeballs = pokemons;
    }

    private int getOccupiedPokeballs() {
        int pokeballs = 0;
        for (Pokemon pokemon : this.pokeballs) {
            if (pokemon != null)
                pokeballs++;
        }
        return pokeballs;
    }

    public String getName() {
        return this.name;
    }

    public boolean throwPokeball(Pokemon pokemonToCatch) {
        if (getOccupiedPokeballs() == this.pokeballs.length) {
            System.out.println("out of pokeballs");
            return false;
        }
        this.pokeballs[getOccupiedPokeballs()+1] = pokemonToCatch;
        return true;
    }

    public Pokemon[] getPokemons() {
        Pokemon[] availablePokemons = new Pokemon[getOccupiedPokeballs()];
        for (int i = 0; i < getOccupiedPokeballs(); i++) {
            availablePokemons[i] = this.pokeballs[i];
        }
        return availablePokemons;
    }

    public abstract boolean fight(Trainer opponent);

    @Override
    public String toString() {
        if (this.pokeballs[0] == null) {
            return this.name + " has no pokemons.";
        }
        StringBuilder result = new StringBuilder(this.name + " pokemons: ");
        for (int i = 0; i < this.pokeballs.length-1; i++) {
            if (this.pokeballs[i] == null)
                continue;
            result.append(this.pokeballs[i] + ", ");
        }
        result.append(this.pokeballs[this.pokeballs.length-1]);
        return result.toString();
    }
}
