import React from 'react';
import '../../css/Views/ticket.css';
import Header from '../Components/Header';
import Navbar from '../Components/Navbar';
import 'react-perfect-scrollbar/dist/css/styles.css';
import Footer from '../Components/Footer';
import { Link } from 'react-router-dom';
import SearchBar from '../Components/SearchBar';
import BarcodeReader from 'react-barcode-reader';
import axios from 'axios';

export default class Stock extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      articles: [],
      scannedCode: ''
    }

    this.handleScan = this.handleScan.bind(this);
  }

  
  getArticles = () => {
    axios.get('https://etud.insa-toulouse.fr/~proximo/v2/api/articles')
        .then(res => {
            this.setState({articles : res.data}, () => {
                console.log(this.state.articles)
            })
        })
        .catch(error => {
            console.log(error.response)
        })
  }

  componentDidMount() {
    this.getArticles();
  }
  
  // RECHERCHE DE L'ARTICLE
  getArticleByCode() {
    let i=0;
    let current = this.state.articles[i];
    let trouve = current === this.state.scannedCode ? true : false;
    while(!trouve) {
      i++;
      current = this.state.articles[i];
      if (current.scannedCode === this.state.scannedCode) {
        trouve = !trouve;
      }
    }
    console.log(current);
  }

  handleScan(code) {
    this.setState({result: code}, () => {
      console.log(this.state.result);
    });
  }

  render() {
    if (!sessionStorage.getItem('token')){
      return (<div id="errorRouteBlock"><div id="errorRouteTitle">ERREUR </div><br/><div id="errorRouteTxt">Vous n'êtes pas connecté</div><br/><Link id="link" to='/'>Retourner à l'Accueil</Link></div>)
    } else {
    return (
        <div id="stock">
            <Header title='Le Ticket de Caisse'/>
            <Navbar redirect="/stock" left="Monnaie" right="Le Stock"/>
            <BarcodeReader onScan={this.handleScan}/>
            <SearchBar/>
            <div id="emptyTicketBox">
              <p id="emptyTicket">
                Scanne tes articles pour remplir le ticket de caisse ! 
              </p>
            </div>
            <Footer/>
        </div>
    )}
  }
}