import React, {useContext} from 'react';
import {addNewProduct, cancelRequest, deleteProduct, getProducts} from '../API/productAPI';
import Loading from '../utility/loading';
import Repository from './repository';
import {ViewContext} from '../app';

const NewButton = ({addNewProductHandler}) => {
    const {adminView} = useContext(ViewContext);

    if (!adminView) {
        return <></>;
    }

    return <button onClick={addNewProductHandler}>Add new product</button>
}

class Products extends React.Component {

    abortController = new AbortController();

    constructor(props) {
        super(props);

        this.state = {
            products: undefined
        }
    }

    addNewProductHandler = async () => {
        await addNewProduct();
        await this.retrieveProducts();
    }

    deleteProductHandler = async (productId) => {
        await deleteProduct(productId);
        await this.retrieveProducts();
    }

    componentDidMount() {
        this.retrieveProducts();
    }

    componentWillUnmount() {
        this.abortController.abort();
    }

    retrieveProducts = async () => {
        const products = await getProducts(this.abortController);
        this.setState({products});
    }

    render() {

        if (!this.state.products) {
            return <Loading/>
        }

        if (this.state.products.length === 0) {
            return <div>There are currently no products available.</div>
        }

        return (
            <div>
                <h2>Products</h2>
                <NewButton addNewProductHandler={this.addNewProductHandler}/>
                {this.state.products
                    .map(p => <Repository key={p.id} {...p} deleteProductHandler={() => this.deleteProductHandler(p.id)}/>)}
            </div>
        );
    }
}

export default Products;
