Newer
Older
pokemon-go-trade / static / html / src / Choose.js
import React, { useEffect, useState } from 'react';
import PokemonList from './components/pokemon-list';
import VariationModal from './components/variation-modal';

export function Choose(props) {
    const { REACT_APP_BACKEND_URL } = process.env;

    let [pokemonList, setPokemonList] =  useState([]);
    let [selectedPokemon, setSelectedPokemon] =  useState(new Map());
    const type = props.type;
    const wantGroupId = props.wantGroupId;
    let [open, setOpen] = useState(false);
    let [selectPokemonGroup, setSelectPokemonGroup] = useState([]);

    useEffect(() => {
        fetch(REACT_APP_BACKEND_URL+'/api/available-pokemon')
            .then(response => response.json())
            .then((data) => {
                setPokemonList(data.pokemons);
            });
    });

    const handleDoneClick = () => () => {
        const pokemons = [];
        selectedPokemon.forEach((pokemon) => {
            pokemons.push(pokemon);
        });
        fetch(REACT_APP_BACKEND_URL+`/api/stored-pokemon?type=${type}&want-group-id=${wantGroupId}`, {
            method: 'POST',
            body: JSON.stringify({pokemons}),
        }).then(() => {
            if (type === 'want') {
                // window.location.href = '/want.html';
            } else {
                // window.location.href = '/index.html';
            }
        });
    };

    const onDeselectPokemon = () => {
        setOpen(false);
        setSelectPokemonGroup([]);
    };

    const onSelectPokemonGroup = (selected, pokemon) => {
        setOpen(true);
        let newSelectPokemonGroup = [pokemon];
        newSelectPokemonGroup = newSelectPokemonGroup.concat(pokemon.variations);
        setSelectPokemonGroup(newSelectPokemonGroup);
    };

    const onSelectPokemon = (selected, pokemon) => {
        let newSelectedPokemon = JSON.parse(JSON.stringify(selectedPokemon))
        if (selected) {
            newSelectedPokemon.set(pokemon.id, pokemon);
        } else {
            newSelectedPokemon.delete(pokemon.id);
        }
        setSelectedPokemon(newSelectedPokemon)
    };

    return (
        <div>
            {props.visible &&
            <div>
            <PokemonList pokemonList={pokemonList} onSelectPokemon={onSelectPokemonGroup}/>
                <VariationModal
                pokemonVariationList={selectPokemonGroup}
                open={open}
                onDeselectPokemon={onDeselectPokemon}
                onSelectPokemon={onSelectPokemon}
                />
                <p style={{height: '10em'}}>{''}</p>
                <button type="button" style={{fontSize: '10em', position: 'fixed', bottom: 0, right: 0}} onClick={handleDoneClick()}>Done</button>
            </div>
            }
        </div>
    );
}