import * as React from 'react';
import * as PropTypes from 'prop-types';

import update from 'immutability-helper';
import axios from 'axios';


import './Zettel.css';
import Besorgung from './Besorgung';
import Zeile from './Zeile';

export default class Zettel extends React.Component {




    state = {
        selectedLine: '',
        liste: [],
    };
    
    getSelectHandler()
    {
        return line => 
        this.setState((state) =>
        update(state, {selectedLine: {$set: line}}),
        );
    }



    async componentDidMount(){

        const {data} = await axios.get('http://localhost:3001/zeile');
        const liste = [];

        data.forEach(zeile => {
            const besorgung = new Besorgung(zeile.nummer, zeile.name, zeile.menge, zeile.einheit, zeile.kommentar);
            liste.push(besorgung);
        });

        this.setState(state =>
            update(state,{
                liste: {$set: liste},
            }),
            );
    }



    render(){
        return(
            <div className="zettel">
                <h1>Einkaufszettel</h1>

                <p>Artikel in der Einkaufsliste = {this.state.liste.length}</p>

                <table>
                    <thead>
                        <tr>
                            {Object.keys(Besorgung.properties).map(property =>{
                                const besorgungsprop = Besorgung.properties[property];
                                return(
                                <th>{besorgungsprop.label}</th>
                                );

                            })}
                        </tr>
                    </thead>
                    <tbody>
                    {
                            this.state.liste.map(zeile => {
                                return(
                                <Zeile
                                    besorgung={zeile}
                                    selectedLine={this.state.selectedLine}
                                    onSelect={this.getSelectHandler()}
                                />
                                );
                            })
                }
                    </tbody>
                </table>
            </div>

        );
    }

}