import axios from 'axios';
import { NavLink, useLocation } from 'react-router-dom';
import React, { useEffect } from 'react';

export default function Navbar() {
    const location = useLocation();

    useEffect(() => {
        const token = localStorage.getItem('TOKEN_TALLER6');
        if (token == null) {
            if (location.pathname !== '/login') {
                window.location = '/login';
            }
            else {
                CheckVigencia();
            }
        }
    }, [location]);

    const CheckVigencia = data => {
        const token = localStorage.getItem('TOKEN_TALLER6');

        const config = {
            headers: { Authorization: `Bearer ${token}` }
        };
        
        const bodyParameters = {
            key: "value"
        };

        axios.post(
            "http://localhost:5000/api/usuario/vigencia",
            bodyParameters,
            config
        )
        .then(
            (response) => {
                console.log(response.data);
            }            
        )
        .catch((err) => {
            if (err.response) {
                console.log(err.response.data.mensaje)
                if(err.response.status === 401){
                    localStorage.removeItem('TOKEN_TALLER6');
                    window.location = '/login';
                }
            }
            else if (err.request) {
                // client never received a response, or request never left
            } 
            else {
                // anything else
            }
        });
    }
    
    if (location.pathname !== '/login') {
        return (
            <div className="topnav">
                <NavLink to="/integrantes">Integrantes</NavLink>
                <NavLink to="/usuarios">Usuarios</NavLink>
            </div> 
        );
    }
    else {
        return (
            <br />
        );
    }
};
