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

const CsvReader = () => {
    const fileStopUnavailable = '/stop\\';
    const fileZoneUnavailable = '/zone\\';

    const [dataStop, setDataStop] = useState([]);
    const [dataZone, setDataZone] = useState([]);
    const [errorStop, setErrorStop] = useState('');
    const [errorZone, setErrorZone] = useState('');
    const [fileStop, setFileStop] = useState(fileStopUnavailable);
    const [fileZone, setFileZone] = useState(fileZoneUnavailable);
    const [isDataStopCompleted,setIsDataStopCompleted] = useState(false);
    const [isDataZoneCompleted,setIsDataZoneCompleted] = useState(false);

    const handleChangeStop = (e) => {
        setErrorStop("");
 
        //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)) {
                setErrorStop("Error! Enter file in CSV format:");
            }else{
		setFileStop(inputFile);
		//console.log('handleChangeStop() file updated');
	    }
        }
    };

    const handleChangeZone = (e) => {
        setErrorZone("");
 
        //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)) {
                setErrorZone("Error! Enter file in CSV format:");
            }else{
		setFileZone(inputFile);
		//console.log('handleChangeZone() file updated');
	    }
	}else{
	    console.error('handleChangeZone() Is this a possible case?');
	}
    };
    const postData = async (requestBody) => {
	//console.log('post() start...');
	//console.log('post() requestBody: ' + JSON.stringify(requestBody));
	/*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.*/
	axios.post('http://localhost:3000/', requestBody).then((rsp)=>{
	    console.log('axios.post() data: ' + rsp.data);
	    if(rsp.data === 'OK'){
		alert('Send succeeded!');
	    }else{
		alert('Send failed!');
	    }
	});
	//console.log('post() done.');
    };

    const updateDataStop = (result) => {
	//console.log('updateDataStop() start...');
	setDataStop(result.data);
	setIsDataStopCompleted(true);
	//console.log('updateDataStop() done.');
    };

    const updateDataZone = (result) => {
	//console.log('updateDataZone() start...');
	setDataZone(result.data);
	setIsDataZoneCompleted(true);
	//console.log('updateDataZone() done.');
    };

    const handleSubmit = (e) => {
	//console.log('handleSubmit() start...');
	e.preventDefault();
        if (fileStop === fileStopUnavailable) {
	    //console.log('handleSubmit() CSV stop file NOT valid');
	    return setErrorStop("Error! Enter a valid CSV stop file:");
	} else if (fileZone === fileZoneUnavailable) {
	    //console.log('handleSubmit() CSV zone file NOT valid');
	    return setErrorZone("Error! Enter a valid CSV zone file:");
	} else {
	    //console.log('handleSubmit() both files valid');
	    Papa.parse(fileStop, {
		complete: updateDataStop,
		header: false,
		encoding: 'ISO-8859-1'
	    });
	    //console.log('handleSubmit() parse called on stops');
	    Papa.parse(fileZone, {
		complete: updateDataZone,
		header: false,
		encoding: 'ISO-8859-1'
	    });
	    //console.log('handleSubmit() parse called on zones');
        }
	//console.log('handleSubmit() done.');
    };

    const handleSend = () => {
	const dataPost = [];
	dataPost[0] = dataStop;
	dataPost[1] = dataZone;
	postData(dataPost);
	setIsDataStopCompleted(false);
	setDataStop([]);
	setErrorStop('');
	setFileStop(fileStopUnavailable);
	setIsDataZoneCompleted(false);
	setDataZone([]);
	setErrorZone('');
	setFileZone(fileZoneUnavailable);
    };

    const ButtonSend = () => {
	if(isDataStopCompleted && isDataZoneCompleted){
	    //console.log('buttonSend() both completed');
	    return(
		<div>
		    <label htmlFor="button-send">4. Send input:</label>
		    <button className ="button-send" id="button-send" type="button" onClick={handleSend}>Send</button>
		</div>
	    );
	}else{
	    //console.log('buttonSend() both NOT completed');
	    return(
		<div>
		    {(!isDataStopCompleted || !isDataZoneCompleted) ? 
		     <label htmlFor="button-send">4. Push Submit before Send!</label> :
		     null}
		    <button type="button" disabled>Send</button>
		</div>
	    );
	}
    };
    return(
	<div className="csv-reader">
	    <h3>CsvReader</h3>
            <form onSubmit={handleSubmit}>
		<label htmlFor="csv-input-stop">{errorStop ? '1. ' + errorStop : '1. CSV stop file:'}</label>
	    <input
		className="csv-input-stop"
		id="csv-input-stop"
		type="file"
		name="file"
		placeholfer={null}
		onChange={handleChangeStop}
	    />
		<br/>
		<label htmlFor="csv-input-zone">{errorZone ? '2. ' + errorZone : '2. CSV zone file:'}</label>
	    <input
		className="csv-input-zone"
		id="csv-input-zone"
		type="file"
		name="file"
		placeholfer={null}
		onChange={handleChangeZone}
	    />
		<br />
		<label htmlFor="button-submit">3. Submit:</label>
            <button type="submit" className="button-submit" id="button-submit">
                Submit
            </button>
	    </form>
	    <ButtonSend />
	</div>
    );
};
 
export default CsvReader;
