import React, { useEffect, useState } from 'react'
import { Link} from 'react-router-dom';
import {useNavigate} from 'react-router-dom';
import axios from 'axios';

export default function Update() {
  
    // Here usestate has been used in order
    // to set and get values from the jsx
    const [name, setName] = useState('');
    const[id,setId] = useState('');
  
    // used for navigation with logic in javascript
    let history = useNavigate()

    async function updateItem(e){
	e.preventDefault();
	//console.log("Home:updateItem() id: " + id);
	//console.log("Home:updateItem() name: " + name);
	const url='https://v1rgncy.api.swingbe.de/entities/'+id+'/update';
	//console.log('Home:updateItem() url: ' + url);
	let data = new FormData();
	data.append('name',name);
	return fetch(url, {
	    method: "POST",
	    mode: "cors",
	    body: data
	})
	    .then(response => {
		if (!response.ok) {
		    console.error('Home:updateItem() rsp error: ' + response);
		}else{
		    //console.log('Home:updateItem() rsp fine');
		    // We need to re-render the page for getting
		    // the results so redirect to same page.
		    history('/')
		    //console.log('Home:updateItem() Done.');
		}
	    })
	    .catch((error) => {
		console.error('Home:updateItem() error: ' + error);
		// We need to re-render the page for getting
		// the results so redirect to same page.
		//console.log('Home:updateItem() Done.');
	    });
    };

    //TODO Why is this function not working?
    const postData = (e) => {
	e.preventDefault();
        console.log('postData() id: '+id);
        console.log('postData() name: '+name);
	const url='https://v1rgncy.api.swingbe.de/entities/'+id+'/update';
        console.log('postData() url: '+url);
	let data = new FormData();
	data.append('name',name);
	let config = {
	    method: 'post',
	    headers: {
		'Content-Type': 'text/plain',
	    },
	    maxBodyLength: Infinity,
	    url: url,
	    data : data
	};
	axios.request(config)
	    .then(rsp => {
		if (!rsp.ok) {
		    console.error('Home:postData() rsp error: ' + JSON.stringify(rsp));
		}else{
		    //console.log('Home:postData() rsp fine');
		    // We need to re-render the page for getting
		    // the results so redirect to same page.
		    history('/')
		    //console.log('Home:postData() Done.');
		}
		console.log('postData() rsp: ' + rsp.data)
	    })
	    .catch((error) => {
		console.error('postData() axios error: '+error);
	    });
    };
    //TODO Why is this function not working?
    const postUpdate = (e) => {
	e.preventDefault();
        console.log('postUpdate() id: '+id);
        console.log('postUpdate() name: '+name);
	const url='https://v1rgncy.api.swingbe.de/entities/'+id+'/update';
        console.log('postUpdate() url: '+url);
	let data = new FormData();
	data.append('name',name);
	//const data = { 'name': name};
	//const data = 'name='+name;
        console.log('postUpdate() data: '+data);
	const headers = {
	    'Content-Type': 'text/plain',
	};
	axios.post(url, data, {headers})
	    .then(rsp => {
		console.log('postData() rsp: ' + rsp.data)
	    })
	    .catch((error) => {
		console.error('postData() axios error: '+error);
	    });
    };

    useEffect(() => {
        setName(localStorage.getItem('rgnCycleName'))
        setId(localStorage.getItem('rgnCycleId'))
    }, [])
    return(
	<div>
	    <h1>Update</h1>
	    <form
		onSubmit={e => updateItem(e)}
	    >
		<label>
		    Enter name (input:{name}):
		    <input
			onChange={e => setName(name => e.target.value)}
			type="text"
			value={name}
			placeholder="Enter Name"
		    />
		</label>
		<button
		    onClick={e => updateItem(e)}
		    type="submit"
		>
		    Update
		</button>
		<Link
		    to='/'
		>
		    <button>
			Home
		    </button>
		</Link>
	    </form>
	</div>
    );
};
