import React, { useState } from 'react';
import Member from './Member';
import empty from '../../img/empty.svg';
import Mech from '../../Mech';
import MechObserver from '../../MechObserver';
import { isEmptySlot } from '../../MechUtils';

function instead<T>(array: T[], index: number, newItem: T): T[] {
    return array.map((item, i) => {
        if (i === index) {
            return newItem;
        } else {
            return item;
        }
    });
}

function hasFreeSlot(squad: Mech[]) {
    return squad.some(isEmptySlot)
}

function isSquadFull(squad: Mech[]) {
    return !hasFreeSlot(squad);
}


function Squad({pickObservers} : {pickObservers: {[key: string] : MechObserver}}) {

    const placeHolder: Mech = {id: -1, name: 'Empty slot', kind: '_', health: 0, move: 0, squad: '_', img: empty};
    const [squadMechs, setSquadMechs] = useState([placeHolder, placeHolder, placeHolder]);
    const [squadName, setSquadName] = useState('Custom squad');

    function putInFreeSlot(mech: Mech, squad: Mech[]): Mech[] {
        const freeSlotIndex = squad.findIndex(isEmptySlot);
        console.log('Next free slot : ', freeSlotIndex);
        return instead(squad, freeSlotIndex, mech);
    }


    function addToSquad(mech: Mech) {
        console.log("New mech to add :", mech)
        if (isSquadFull(squadMechs)) {
            console.log("Squad is full, sorry");
            return;
        }

        setSquadMechs(putInFreeSlot(mech, squadMechs));
    }

    function removeFromSquad(index: number) {
        setSquadMechs(instead(squadMechs, index, placeHolder));
    }

    pickObservers.addWhenPicked = addToSquad;

    return (
        <article className='custom-squad'>
            <h2>{squadName}</h2>
            <div className='mech-members'>
                {squadMechs.map((m, index) => (
                    <Member key={index} mech={m} remover={() => removeFromSquad(index)}/>
                ))}
            </div>
            <div className='squad-description'>
                <label htmlFor='squad-name-field-id'>Squad name</label>
                <input id='squad-name-field-id' defaultValue='Custom squad' value={squadName} onChange={change => setSquadName(change.target.value)}/>
                <label htmlFor='squad-description-field-id'>Squad description</label>
                <textarea id='squad-description-field-id' defaultValue='A powerful squad.'/>
            </div>
        </article>
    )
}

export default Squad;