import React, { useState } from "react";
import Papa from "papaparse";
import axios from 'axios';
 
const allowedExtensions = ["csv"];

const CsvReader = () => {
    const [data, setData] = useState([]);
    const [error, setError] = useState("");
    const [file, setFile] = useState("");
    const handleChange = (e) => {
        setError("");
 
        //check if user has entered the file
        if (e.target.files.length) {
            const inputFile = e.target.files[0];
 
            //check the file extensions
            const fileExtension = inputFile?.type.split("/")[1];
            if (!allowedExtensions.includes(fileExtension)) {
                setError("Please input a csv file");
            }else{
		setFile(inputFile);
		console.log('handleChange() file updated');
	    }
        }
    };
    const post = async (requestBody) => {
	console.log('post() start...');
	console.log('post() requestBody: ' + JSON.stringify(requestBody));
	console.log('post() before post');
	/*If you pass a JavaScript object as the 2nd parameter to the axios.post() function, Axios will automatically serialize the object to JSON for you. Axios will also set the Content-Type header to 'application/json', so web frameworks like Express can automatically parse it.*/
	const data = await axios.post('http://localhost:3000/', requestBody).then(res => res.data);
	console.log('post() after post');
	console.log('post() json data: ' + JSON.stringify(data));
	console.log('post() done.');
    };
    const handleParse = () => {
	console.log('handleParse() start ...');
        if (!file) {
	    console.log('handleParse() file NOT valid');
	    return setError("Enter a valid file");
	} else {
	    console.log('handleParse() file valid');
	    Papa.parse(file, {
		complete: updateData,
		header: false,
		encoding: 'ISO-8859-1'
	    });
        }
	console.log('handleParse() done.');
    };
    const updateData = (result) => {
	console.log('updateData() start...');
	let data = result.data;
	setData(data);
	post(data);
	console.log('updateData() done.');
    };
    return(
	<div className="csv-reader">
	    <h3>CsvReader</h3>
            <label
		htmlFor="csv-input"
	    >
                Enter CSV File:
            </label>
	    <input
		className="csv-input"
		id="csv-input"
		type="file"
		name="file"
		placeholfer={null}
		onChange={handleChange}
	    />
	    <div>
		<button onClick={handleParse}>Parse</button>
	    </div>
	    <div>
		{error ? error : data.map((value, idx) => {
		    return <div key={idx}>
			       {JSON.stringify(value)}
			   </div>}
					 )}
	    </div>
	</div>
    );
};
 
export default CsvReader;
