import React from 'react';
import '../../css/Components/articlesbycategory.css'
import ArticleDetails from './ArticleDetails'

class ArticlesByCategory extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            mouseEnter:false,
            articles:this.props.articles
        }
    }

    componentDidMount(){
      this.splitArticlesCategories()
    }

    componentDidUpdate(){
        
        if (this.props.onSearch){
        // implémenter une fonction de recherche en React sur articles
        }
    }

    splitArticlesCategories = () => {
        let counterTab = 0;
        let divided = [];
        divided.push([this.state.articles[0]])
        for (let i = 1; i<this.state.articles.length;i++){
          if (this.state.articles[i].category_id === this.state.articles[i-1].category_id){
            divided[counterTab].push(this.state.articles[i])
          } else {
           counterTab++
           divided.push([this.state.articles[i]])
          }
        }
        this.setState({articles:divided},()=>{
          console.log(this.state.articles)
        })
        
      }

    
    render() {
        console.log(this.state.articles)
      return (
          <div id="articleContainer">
            <div id="articles">
                {this.state.articles[0][0] &&
                    this.state.articles.map((divided) => 
                        <div id="categoryBlock">
                            <p id="categoryName">{divided[0].category.name}</p>
                            <div id="underlinment"></div>
                            <div id="bulles">
                                {divided.map((article) =>
                                <ArticleDetails handleCategories={this.props.handleCategories} editArticle={this.props.editionArticle} key={article.id} id={article.id} name={article.name} img={article.image} desc={article.description} price={article.price} quantity={article.quantity} code={article.code} category={article.category}/>
                                )}
                            </div>
                        </div>
                    )
                }
            </div>
          </div>
      )
    }
  }

  export default ArticlesByCategory